leetcode 404 Sum of Left Leaves

来源:互联网 发布:成都闪电seo 编辑:程序博客网 时间:2024/06/10 02:17

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;    }};
1 0
原创粉丝点击