404. Sum of Left Leaves

来源:互联网 发布:二端口ucd=0.1 编辑:程序博客网 时间:2024/04/30 17:21

Find the sum of all left leaves in a given binary tree.

Example:

    3   / \  9  20    /  \   15   7There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.



计算左子树叶节点的值的总和。用dfs和bfs都可以,递归和不递归都可以。用dfs时,判断如果是叶节点而且是左子树的就累加。注意只有根结点的情况下,根结点不算左子树叶节点。

代码:
class Solution{public:int sumOfLeftLeaves(TreeNode* root){return dfs(root, false);}private:int dfs(TreeNode* root, bool isleft){if(!root) return 0;if(!root->left && !root->right){return isleft ? root->val : 0;}return dfs(root->left, true) + dfs(root->right, false);}};


0 0
原创粉丝点击