原题
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;
}