leetcode_404. Sum of Left Leaves-左叶子的和

来源:互联网 发布:家用配电箱品牌知乎 编辑:程序博客网 时间:2024/05/29 04:04

查找二叉树所有左叶子的和。

法1:

public int sumOfLeftLeaves(TreeNode root) {    if(root == null) return 0;    int ans = 0;    if(root.left != null) {        if(root.left.left == null && root.left.right == null) ans += root.left.val;        else ans += sumOfLeftLeaves(root.left);    }    ans += sumOfLeftLeaves(root.right);    return ans;}

法2:

public int sumOfLeftLeaves(TreeNode root) {    if(root == null) return 0;    int ans = 0;    Stack<TreeNode> stack = new Stack<TreeNode>();    stack.push(root);    while(!stack.empty()) {        TreeNode node = stack.pop();        if(node.left != null) {            if (node.left.left == null && node.left.right == null)                ans += node.left.val;            else                stack.push(node.left);        }        if(node.right != null) {            if (node.right.left != null || node.right.right != null)                stack.push(node.right);        }    }    return ans;}
0 0
原创粉丝点击