【LeetCode】404 Sum of Left Leaves(java实现)

原题

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

    3
   / \
  9  20
    /  \
   15   7
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

题目要求

题目叫“左叶子节点之和”,题目比较清晰,有一棵树,求出树种所有左叶子节点的和。

解法

解法一:这种解法比较直接,对于这种问题,递归的方式比较容易理解。这里需要注意两点:一,必须是左边的叶子节点;二,如果数只有根节点,根节点不是叶子节点,更不是左叶子节点。

public int sumOfLeftLeaves(TreeNode root, Boolean isLeft) {
    if (root == null) {
        return 0;
    }
    int sum = 0;
    if (root.left != null || root.right != null) {
        sum += sumOfLeftLeaves(root.left, true);
        sum += sumOfLeftLeaves(root.right, false);
    }else if (isLeft) {
        sum += root.val;
    }

    return sum;
}

public int sumOfLeftLeaves(TreeNode root) {
    return sumOfLeftLeaves(root, false);
}

解法二:很多人不喜欢递归,认为性能不好,这里我再提供一种非递归的思路。一般来说,想用非递归的思路来实现递归的效果,就是使用栈(stack),因为递归的实现就是潜在地使用了栈的思路。这里,我们只需要使用深度优先的方式来遍历节点,并把所有节点放入栈(push)中,之后再取出(pop)即可。 这里列出别人给出的方法:

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值