2017年12月16日 星期六

[LeetCode] 404. Sum of Left Leaves

轉自LeetCode

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
/**
* 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
/**
* 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);
}
};

沒有留言:

張貼留言