Find the sum of all left leaves in a given binary tree.
Example:node
3 / \ 9 20 / \ 15 7 There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
题目叫“左叶子节点之和”,题目比较清晰,有一棵树,求出树种全部左叶子节点的和。性能
解法一:这种解法比较直接,对于这种问题,递归的方式比较容易理解。这里须要注意两点:一,必须是左边的叶子节点;二,若是数只有根节点,根节点不是叶子节点,更不是左叶子节点。code
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; }