LeetCode404. Sum of Left Leaves所有左叶节点的和 #算法# 第十四周

2022-06-23 11:26:39 浏览数 (1)

原题

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

Example:

代码语言:javascript复制
    3
   / 
  9  20
    /  
   15   7

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

思路

可以用递归的思想, (1)若节点为空,则为0; (2)若左子节点为叶子节点,则加上其值,否则加上左子节点的所有左叶节点的和 (3)再加上右子节点的所有左叶子节点的和

代码

代码语言:javascript复制
class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        if(root == NULL) return 0;
        int ans = 0;
        if(root->left != NULL){
            if(root->left->left == NULL && root->left->right == NULL)
                ans  = root->left->val;
            else
                ans  = sumOfLeftLeaves(root->left);
        }
        ans  = sumOfLeftLeaves(root->right);
        return ans;
    }
};

0 人点赞