404. 左叶子之和
404. Sum of Left Leaves
LeetCode404. Sum of Left Leaves
题目描述
计算给定二叉树的所有左叶子之和。
示例:
3
/
9 20
/
15 7
在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24。
Java 实现
TreeNode 结构
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
Recursive
class Solution {
private int sum = 0;
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left != null && root.left.left == null && root.left.right == null) {
sum += root.left.val;
}
sumOfLeftLeaves(root.left);
sumOfLeftLeaves(root.right);
return sum;
}
}
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
int count = 0;
if (root == null) {
return 0;
}
if (root.left != null) {
if (root.left.left == null && root.left.right == null) {
count += root.left.val;
} else {
count += sumOfLeftLeaves(root.left);
}
}
count += sumOfLeftLeaves(root.right);
return count;
}
}
Iterative
import java.util.Stack;
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
int count = 0;
Stack<TreeNode> stack = new Stack<>();
if (root == null) {
return 0;
}
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
if (node.left != null) {
if (node.left.left == null && node.left.right == null) {
count += 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 count;
}
}
主测试类
public class Test {
public static void main(String[] args) {
Solution tree = new Solution();
/* create a tree */
TreeNode root = new TreeNode(3);
root.left = new TreeNode(9);
root.right = new TreeNode(20);
root.right.left = new TreeNode(15);
root.right.right = new TreeNode(7);
System.out.println(tree.sumOfLeftLeaves(root));
}
}
运行结果
24
相似题目
参考资料