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: Python]404. Sum of Left Leaves
- LeetCode 404. Sum of Left Leaves
- leetcode 404. Sum of Left Leaves
- LeetCode笔记:404. Sum of Left Leaves
- LeetCode—404. Sum of Left Leaves
- LeetCode 404. Sum of Left Leaves 解题报告
- [leetcode]: 404. Sum of Left Leaves
- [LeetCode]404. Sum of Left Leaves
- 【LeetCode】 404. Sum of Left Leaves
- leetcode 404. Sum of Left Leaves
- 【Leetcode】404. Sum of Left Leaves
- LeetCode 404. Sum of Left Leaves
- LeetCode 404. Sum of Left Leaves (左子叶之和)
- leetcode 404. Sum of Left Leaves
- 小白笔记----------------leetcode(404. Sum of Left Leaves )
- leetcode_404. Sum of Left Leaves-左叶子的和
- leetcode-404. Sum of Left Leaves 求左叶子节点的和,递归
- LeetCode 404. Sum of Left Leaves (二叉树,递归)
- LeetCode 404. Sum of Left Leaves
- LeetCode 404. Sum of Left Leaves