leetcode 404. Sum of Left Leaves

来源:互联网 发布:teambition类似软件 编辑:程序博客网 时间:2024/06/06 10:53

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

如果采用递归的解法,就需要判断前后两次迭代的关系。
如果树只有一个节点,需要判断其与父节点的关系,如果该节点是左孩子,就直接返回其值,如果是右孩子就返回0。如果还有孩子,就往下递归。
注意到这里有个与父节点关系,按照一般的递归是无法保持这个信息,同时为了递归的简便,不太方便在每次递归里还判断下两层的情况,最好只看是判断有无孩子。这样我们可以设置一个标志位,来记住进入该节点时,该节点与父节点的关系。默认根节点是父节点的右孩子。

/** * 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;        res = left_sum(root,1);        return res;    }    //dir, 0:left, 1:right    int left_sum(TreeNode root, int dir){        int res = 0;        if(root.left==null && root.right==null){            if(dir==0) return root.val;            else return 0;        }        if(root.left!=null) res += left_sum(root.left, 0);        if(root.right!=null) res += left_sum(root.right,1);        return res;    }}
原创粉丝点击