Sum of Left Leaves

来源:互联网 发布:三星s4可以用4g网络吗 编辑:程序博客网 时间:2024/04/30 13:23

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

Example:

    3   / \  9  20    /  \   15   7There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
思路:典型的dfs,preorder,也就是先把满足条件的写了,然后搜索左右两个子树。

满足条件的node要有两个属性:

1. 是最左点。

2. 而且最左点没有左右孩子,表明是leave。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int sumOfLeftLeaves(TreeNode root) {        if(root == null) return 0;        int[] res = {0};        collect(root, res);        return res[0];    }        public void collect(TreeNode root, int[] res){        if(root == null) return;        if(root.left!=null){            if(root.left.left == null && root.left.right == null){                res[0] += root.left.val;            }        }        collect(root.left, res);        collect(root.right, res);    }}


1 0
原创粉丝点击