2016/10/12 10:05

# 原题

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);
}
``````

``````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 评论
0 收藏
0