美文网首页
404. Sum of Left Leaves 左叶子的和

404. Sum of Left Leaves 左叶子的和

作者: 这就是一个随意的名字 | 来源:发表于2017-07-30 10:11 被阅读0次

Find the sum of all left leaves in a given binary tree.
对给定的二叉树,返回其左叶子的和。
Example:

    3
   / \
  9  20
    /  \
   15   7

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.


思路
遍历整棵树,注意判定条件不是当前节点是不是叶子,而是当前节点有没有左叶子结点,有则计入总和,没有则在左右子树递归遍历。

/**
 * 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) {
        int res=0;
        if(!root || (!root->left && !root->right)) return 0;
        if(root->left && (!root->left->left && !root->left->right)) res+=root->left->val;
        res+=sumOfLeftLeaves(root->left);
        res+=sumOfLeftLeaves(root->right);
        return res;
    }
};

相关文章

网友评论

      本文标题:404. Sum of Left Leaves 左叶子的和

      本文链接:https://www.haomeiwen.com/subject/tauhlxtx.html