(Leetcode)404. 左叶子之和

题目

题目链接 https://leetcode-cn.com/problems/sum-of-left-leaves/
计算给定二叉树的所有左叶子之和。

示例:

    3
   / \
  9  20
    /  \
   15   7

在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
 

Related Topics
树

代码

我们都知道求所有的节点的和

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
       return solve(root);
    }
    public int solve(TreeNode root){
        if(root==null){
            return 0;
        }
        int left = solve(root.left);
        int right = solve(root.right);
        return root.val+left+right;
    }
}

在基础上改一改可以求所有叶子节点的和

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
       return solve(root);
    }
    public int solve(TreeNode root){
        if(root==null){
            return 0;
        }
        int sum=0;
        // 叶子节点
        if (root.left == null && root.right == null) {
            sum = root.val;
        }
        int left = solve(root.left);
        int right = solve(root.right);
        return sum+left+right;
    }
}

在改一改就可以求所有左节点的和了

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
       return solve(root,false);
    }
    public int solve(TreeNode root,boolean flag){
        if(root==null){
            return 0;
        }
        int sum=0;
        // 叶子节点
        if (flag&&root.left == null && root.right == null) {
            sum = root.val;
        }
        int left = solve(root.left,true);
        int right = solve(root.right,false);
        return sum+left+right;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章