Skip to content

Commit 3974bbd

Browse files
committed
新增5题,累积18题
1 parent a9e3222 commit 3974bbd

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed

src/com/cjl/common/TreeNode.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,13 @@ public class TreeNode {
44
public int val;
55
public TreeNode left;
66
public TreeNode right;
7+
public TreeNode() {}
78
public TreeNode(int x) {
89
val = x;
910
}
11+
public TreeNode(int val, TreeNode left, TreeNode right) {
12+
this.val = val;
13+
this.left = left;
14+
this.right = right;
15+
}
1016
}
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
package com.cjl.leetcode;
2+
3+
import com.cjl.common.ListNode;
4+
import com.cjl.common.TreeNode;
5+
6+
import java.util.*;
7+
import java.util.concurrent.BlockingDeque;
8+
9+
/*
10+
199. 二叉树的右视图
11+
问题描述:
12+
给定一个二叉树的 根节点 root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
13+
示例 1:
14+
输入:[1,2,3,null,5,null,4]
15+
输出:[1,3,4]
16+
示例 2:
17+
输入:[1,null,3]
18+
输出:[1,3]
19+
示例 3:
20+
输入:[]
21+
输出:[]
22+
提示:
23+
二叉树的节点个数的范围是 [0,100]
24+
-100<= Node.val <= 100
25+
*/
26+
public class Question_199 {
27+
28+
// DFS 深度遍历算法
29+
// 时间复杂度是O(N),空间复杂度是O(N)
30+
public List<Integer> solution1(TreeNode root) {
31+
List<Integer> res = new ArrayList<>();
32+
recur(root,0,res);
33+
return res;
34+
}
35+
36+
private void recur(TreeNode root, int level, List<Integer> res) {
37+
if (root == null) {
38+
return;
39+
}
40+
// 先访问 当前节点,再递归地访问 右子树 和 左子树。
41+
if (level == res.size()) {
42+
// 如果当前节点所在深度还没有出现在res里,说明在该深度下当前节点是第一个被访问的节点,因此将当前节点加入res中。
43+
res.add(root.val);
44+
}
45+
level++;
46+
recur(root.right, level, res);
47+
recur(root.left, level, res);
48+
}
49+
50+
// BFS 广度遍历算法
51+
// 时间复杂度是O(N),空间复杂度是O(N)
52+
public List<Integer> solution2(TreeNode root) {
53+
List<Integer> res = new ArrayList<>();
54+
if(root == null){
55+
return res;
56+
}
57+
Queue<TreeNode> queue = new LinkedList<>();
58+
queue.offer(root);
59+
while(!queue.isEmpty()) {
60+
int size = queue.size();
61+
for (int i = 0; i < size; i++) {
62+
TreeNode node = queue.poll();
63+
if(node.left != null) {
64+
queue.offer(node.left);
65+
}
66+
if(node.right != null) {
67+
queue.offer(node.right);
68+
}
69+
if(i == size - 1) {
70+
// 当前层最后一个节点存入数据
71+
res.add(node.val);
72+
}
73+
}
74+
}
75+
return res;
76+
}
77+
}

0 commit comments

Comments
 (0)