题目:
计算给定二叉树的所有左叶子之和。
示例:
3
/ \
9 20
/ \
15 7
在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24解题思路:
遍历二叉树,求和左叶子节点的值。
注意只有一个根节点的时候根节点的值不算。
代码实现:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int sumOfLeftLeaves(TreeNode root) { if (root == null) return 0; int sum = 0; Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode p = root; if (p.left == null && p.right == null) p = null; while (p != null) { if (p.right != null) stack.push(p.right); p = p.left; if (p != null && p.left == null && p.right == null) sum += p.val; if (p == null && !stack.isEmpty()) { p = stack.pop(); } } return sum; } }
二叉树左叶子之和算法
本文介绍了一种计算二叉树所有左叶子节点之和的方法。通过遍历二叉树并累加符合条件的左叶子节点的值,最终得出总和。特别地,仅包含一个根节点的树不计入总和。
781

被折叠的 条评论
为什么被折叠?



