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.
/**
* 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) {
int ans = 0;
TreeNode *prev = NULL;
helper(root, NULL, ans);
return ans;
}
void helper(TreeNode* root, TreeNode *prev, int& ans) {
if (root == NULL) {
return;
}
if (prev == NULL) {
helper(root -> left, root, ans);
helper(root->right, NULL, ans);
return;
}
if (root -> left == NULL && root -> right == NULL && root == prev -> left) {
ans += root -> val;
}
prev = root;
helper(root -> left, prev, ans);
helper(root -> right, NULL, ans);
return;
}
};
==== Simpler ======
class Solution { private: int res=0; void dfs(TreeNode* node, bool isLeft) { // root为叶子的情况 if(node->left == NULL && node->right == NULL) { if(isLeft) res+=node->val; return; } if(node->left!=NULL) dfs(node->left, true); if(node->right!=NULL) dfs(node->right, false); } public: int sumOfLeftLeaves(TreeNode* root) { if(!root) return 0; dfs(root, false); return res; } };
No comments:
Post a Comment