您的位置:首页 > 其它

leetcode 404 Sum of Left Leaves

2017-02-06 00:19 288 查看
Problem:

给一颗二叉树,求这棵树的左叶子节点之和。

Solution:

dfs搜一下即可。

notes:

1. 默认参数的应用。

2. 要注意root可能为空,如果为空则不能方位它的左值,所以要处理这个异常。

class Solution {
public:
int sumOfLeftLeaves(TreeNode* root, bool isLeft = false) {
int ans = 0;

if(!root)
return 0;
if(isLeft && !root->left && !root->right)
ans += root->val;
else {
ans += sumOfLeftLeaves(root->left, true);
ans += sumOfLeftLeaves(root->right);
}

return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: