Find the sum of all left leaves in a given binary tree.
Example:
3 / \ 9 20 / \ 15 7 There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.<Solution>
通常 tree 的問題,不是 DFS 就是 BFS
那實作的方式,就有 iterative 和 recursive 兩種
這邊就按照提意來寫就可以
code 如下
C++,Iterative
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for a binary tree node. | |
* struct TreeNode { | |
* int val; | |
* TreeNode *left; | |
* TreeNode *right; | |
* TreeNode(int x) : val(x), left(NULL), right(NULL) {} | |
* }; | |
*/ | |
class Solution { | |
public: | |
int sumOfLeftLeaves(TreeNode* root) { | |
stack<TreeNode *> stack; | |
if(root) { | |
stack.push(root); | |
} | |
int ans = 0; | |
TreeNode *cur; | |
while(!stack.empty()) { | |
cur = stack.top(); | |
stack.pop(); | |
if(cur->left) { | |
if(!cur->left->left && !cur->left->right) { | |
//>> left leaf | |
ans += cur->left->val; | |
} | |
else { | |
//>> left childs | |
stack.push(cur->left); | |
} | |
} | |
//>> only push right child | |
if(cur->right && (cur->right->left || cur->right->right)) { | |
stack.push(cur->right); | |
} | |
} | |
return ans; | |
} | |
}; |
C++,Recursive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for a binary tree node. | |
* struct TreeNode { | |
* int val; | |
* TreeNode *left; | |
* TreeNode *right; | |
* TreeNode(int x) : val(x), left(NULL), right(NULL) {} | |
* }; | |
*/ | |
class Solution { | |
public: | |
int sumOfLeftLeaves(TreeNode* root) { | |
return findSum(root, false); | |
} | |
int findSum(TreeNode *node, bool isLeft) { | |
if(!node) { | |
return 0; | |
} | |
if(!node->left && !node->right) { | |
return isLeft ? node->val : 0; | |
} | |
return findSum(node->left, true) + findSum(node->right, false); | |
} | |
}; |
沒有留言:
張貼留言