Sum of Left Leaves

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

Divide and Conquer

Time Complexity
O(N)
Space Complexity
O(logn)

思路

这题的题意可以转换为看对于整颗树的每一个Node,它的左子树是否是leaf node,是的话,相加。所以有两层判断,一层是是否是左子树,一层是是否是leaf node。

代码

public int sumOfLeftLeaves(TreeNode root) {
    boolean leftTree = false;
    return helper(root, leftTree);
}

private int helper(TreeNode root, boolean leftTree){
    if(root == null) return 0;
    int left = helper(root.left, true);
    int right = helper(root.right, false);
    if(root.left == null && root.right == null){
        if(leftTree){
            return root.val;
        }else return 0;
    }
    return left + right;
}

annielulu
5 声望5 粉丝

引用和评论

0 条评论