力扣每日一题,404. 左叶子之和
我以为1ms够快了,万万没想到个个都是0ms,太强了。
题目描述
计算给定二叉树的所有左叶子之和。
示例:
3 / \ 9 20 / \ 15 7 在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
思路
还是复习遍历的简单题,把遍历模板烂熟于心吧。
二叉树前序遍历模板(迭代实现)
import java.util.Stack;
public class Solution {
public static void main(String[] args) {
/*
* 5
* / \
* 4 3
* / \
* 1 2
*/
TreeNode root = new TreeNode(5);
root.left = new TreeNode(4);
root.right = new TreeNode(3);
root.left.left = new TreeNode(1);
root.left.right = new TreeNode(2);
new Solution().preOrder(root);
}
// 迭代实现
void preOrder(TreeNode root) {
if (root != null) {
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
System.out.print(node.val + " ");
if (node.right != null)
stack.push(node.right);
if (node.left != null)
stack.push(node.left);
}
}
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
提交代码
套用模板,需增加的地方是,每次处理左子树的时候判断下是不是叶子,是就将值加给sum
package 左叶子之和;
import java.util.Deque;
import java.util.LinkedList;
import org.junit.Test;
public class Solution {
@Test
public void test1() throws Exception {
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);
sumOfLeftLeaves(root);
}
public int sumOfLeftLeaves(TreeNode root) {
if (root != null){
Deque<TreeNode> queue = new LinkedList<TreeNode>();
queue.push(root);
int sum = 0;
while (!queue.isEmpty()) {
root = queue.pop();
if (root.right != null) {
queue.push(root.right);
}
if (root.left != null) {
if (root.left.left == null && root.left.right == null) {
sum += root.left.val;
}
queue.push(root.left);
}
}
return sum;
}
return 0;
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}