zl程序教程

您现在的位置是:首页 >  其它

当前栏目

leetcode404. 左叶子之和

叶子
2023-09-27 14:25:55 时间

计算给定二叉树的所有左叶子之和。

示例:

    3
   / \
  9  20
    /  \
   15   7

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

思路:遍历二叉树找到叶子加起来,判断如果是右叶子就减去。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        if(root==null)return 0;
        if(root.left==null && root.right==null)return 0;
        return help(root);
    }
    public int help(TreeNode root) {
        if(root==null) return 0;
        if(root.left==null && root.right==null) return root.val;
        int r=0;
        if(root.right!=null && root.right.left==null && root.right.right==null)r=root.right.val;
        return help(root.left)+help(root.right)-r;
    }
}