1254. Sum of Left Leaves

描述

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

您在真实的面试中是否遇到过这个题?  

样例

    3
   / \
  9  20
    /  \
   15   7

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

比较简单,递归遍历就可以了。

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: t
     * @return: the sum of all left leaves
     */
    int sumOfLeftLeaves(TreeNode * root) {
        // Write your code here
        if(root==NULL) return 0;
        int sum=0;
        if(root->left!=NULL&&root->left->left==NULL&&root->left->right==NULL) 
            sum+=root->left->val;
        sum += sumOfLeftLeaves(root->left);
        sum += sumOfLeftLeaves(root->right);
        return sum;
    }
};

猜你喜欢

转载自blog.csdn.net/vestlee/article/details/80725673
今日推荐