美文网首页
404. Sum of Left Leaves

404. Sum of Left Leaves

作者: namelessEcho | 来源:发表于2017-09-22 11:21 被阅读0次

找到所有左侧叶子结点的和。

稍微改变一下递归链,我们不递归右边的叶子结点,还有这个函数对于root是leaf的时候需要特殊判断

/**
 * 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(isLeaf(root)) return 0;
       return search_left_leaves(root);
    }
    private int search_left_leaves(TreeNode root)
    {
        if(root==null) return 0;
        if(isLeaf(root)) return root.val;
        int left = 0 ;
        int right= 0 ;
        left=search_left_leaves(root.left);
        if(!isLeaf(root.right))
        right=search_left_leaves(root.right);
        return left+right;
            
    }
    private boolean isLeaf(TreeNode root)
    {
        if(root==null) return false;
        return  root.left==null&&root.right==null;
    }
}

相关文章

网友评论

      本文标题:404. Sum of Left Leaves

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