您的位置:首页 > 其它

LeetCode 404. Sum of Left Leaves

2016-10-19 13:22 393 查看

描述

给出一棵二叉树,求所有左叶子节点的数值和

解决

就递归,找到左叶子节点就加起来。注意不要sf了。

/**
* 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) {
if (root)
{
myFunc(root, root -> left);
myFunc(root, root -> right);
}
return sum;
}
void myFunc(TreeNode* root, TreeNode* child)
{
if (root -> left == child && child && child -> left == NULL && child -> right == NULL)
{
sum += child -> val;
return ;
}
if (root -> left == NULL && root -> right == NULL)
return ;
if (child)
{
myFunc(child, child -> left);
myFunc(child, child -> right);
}
}
Solution() : sum(0) {}
private:
int sum;
};


别人的一份很简洁的代码

/**
* 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) {
if (!root) return 0;
if (root->left && !root->left->left && !root->left->right)
return root->left->val + sumOfLeftLeaves(root->right);
return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode