814. Binary Tree Pruning

814. Binary Tree Pruning

Question

Given the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed.

A subtree of a node node is node plus every node that is a descendant of node.

Solution 1

DFS搜索,首先递归两个子节点。
在搜索时如果节点为0且两个子节点均为null,则返回null。否则返回节点本身。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode pruneTree(TreeNode root) {
if(root == null) return null;
root.left = pruneTree(root.left);
root.right = pruneTree(root.right);
if(root.left == null && root.right == null && root.val == 0) return null;
else return root;
}
}

Solution 2

DFS搜索,返回子节点和自己中是否包含1。
如果节点为null,则返回false。
如果自己为1,则返回true。
否则返回两个子节点中是否有true。

BFS搜索,根据每个节点的子节点是否包含1来决定左右子节点是否保存。
如果没有1,则将对应的子节点修改为null。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode pruneTree(TreeNode root) {
if(!hasOne(root)) return null;
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while(!q.isEmpty()){
TreeNode curr = q.poll();
if(hasOne(curr.left)) q.add(curr.left);
else curr.left = null;
if(hasOne(curr.right)) q.add(curr.right);
else curr.right = null;
}
return root;
}

private boolean hasOne(TreeNode root){
if(root == null) return false;
if(root.val == 1) return true;
else return hasOne(root.left) || hasOne(root.right);
}
}
429. N-ary Tree Level Order Traversal

429. N-ary Tree Level Order Traversal

Question

Given an n-ary tree, return the level order traversal of its nodes’ values.

Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).

Solution

BFS搜索,层序遍历。
用level记录上一层的个数。
当队列不为空时,每次挤出level个节点,并将其子节点加入队列。
将当前层次的节点值加入列表。
最后更新level的数量。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;

public Node() {}

public Node(int _val) {
val = _val;
}

public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
};
*/

class Solution {
public List<List<Integer>> levelOrder(Node root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null) return res;
Queue<Node> q = new LinkedList<>();
q.add(root);
int level = 1;

while(!q.isEmpty()){
List<Integer> arr = new ArrayList<>();
for(int i = 0; i < level; i++){
Node curr = q.poll();
for(Node child : curr.children){
q.offer(child);
}
arr.add(curr.val);
}
res.add(arr);
level = q.size();
}
return res;
}
}
637. Average of Levels in Binary Tree

637. Average of Levels in Binary Tree

Question

Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10<sup>-5</sup> of the actual answer will be accepted.

Solution

BFS搜索,记录单层的总和sum和单层的个数count。
每次遍历一个层级的所有节点,并更新sum和count。
遍历完毕后将当层级的平均数加入列表,同时将sum和count清零。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Double> averageOfLevels(TreeNode root) {
List<Double> res = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<>();

double sum = 0, count = 0;
int level = 1;
q.add(root);

while(!q.isEmpty()){

for(int i = 0; i < level; i++){
TreeNode curr = q.poll();
if(curr.left != null) q.add(curr.left);
if(curr.right != null) q.add(curr.right);
count++;
sum += curr.val;
}
res.add(sum/count);
sum = 0;
count = 0;
level = q.size();
}
return res;
}
}
1302. Deepest Leaves Sum

1302. Deepest Leaves Sum

Question

Given the root of a binary tree, return the sum of values of its deepest leaves.

Solution

BFS搜索,层序遍历,每次计算每个层级的总和。
最后返回最后一个层级总和。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int deepestLeavesSum(TreeNode root) {
Deque<TreeNode> q = new LinkedList<>();
int res = 0;

q.offer(root);

int level = q.size();

while(!q.isEmpty()){
int sum = 0;
for(int i = 0; i < level; i++){
TreeNode curr = q.poll();
sum += curr.val;
if(curr.left != null) q.offer(curr.left);
if(curr.right != null) q.offer(curr.right);
}
res = sum;
level = q.size();
}
return res;
}
}
130. Surrounded Regions

130. Surrounded Regions

Question

Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally surrounded by 'X'.

A region is captured by flipping all 'O's into 'X's in that surrounded region.

Solution

首先对所有在边缘上的“O”进行BFS或DFS搜索,将和边缘连续的“O”改为“#”或任意其他字符。

然后遍历整个board,如果是“O”则改为“X”,如果是“#”则恢复为“O”。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
public void solve(char[][] board) {
for(int i = 0; i <board.length; i++){
for(int j = 0; j <board[0].length; j++){
boolean isEdge = (i == 0 || j == 0 || i == board.length-1 || j == board[0].length-1);
if(isEdge && board[i][j] == 'O'){
bfs(board, i, j);
}
}
}
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
if(board[i][j] == '#') board[i][j] = 'O';
else if(board[i][j] == 'O') board[i][j] = 'X';
}
}
}

private void bfs(char[][] board, int x, int y){
int m = board.length;
int n = board[0].length;
Queue<int[]> q = new LinkedList<>();
q.add(new int[]{x, y});
int size = 1;
while(!q.isEmpty()){
for(int k = 0; k < size; k++){
int[] curr = q.poll();
int i = curr[0], j = curr[1];
if( i<0 || j<0 || i>m-1 || j>n-1 || board[i][j] == 'X' || board[i][j] == '#' ) continue;
board[i][j] = '#';
q.add(new int[]{i+1,j});
q.add(new int[]{i-1,j});
q.add(new int[]{i,j+1});
q.add(new int[]{i,j-1});
}
size = q.size();
}
}
}
297. Serialize and Deserialize Binary Tree

297. Serialize and Deserialize Binary Tree

Question

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

Clarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

Solution

编码过程

编码时采用BFS搜索,将二叉树按层级组成字符串。
当当前节点不等于null时,添加当前节点的值和一个符号。
然后将其左右子节点加入队列。
当当前节点为null时,添加一个非数字字符和一个符号。

解码过程

解码时同样采用BFS搜索,按层级恢复二叉树。
首先将字符串根据符号进行分割,变为字符串数组。
如果第一个字符表示为null,返回null。

否则将第一个数字组成根节点并加入队列。创建一个指针i记录位置。
当队列不为空,且指针i未越界时,根据指针i上的字符串创建当前节点的左子节点。
将指针右移,如果没有越界则创建当前节点的右子节点,然后将指针右移。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {

// Encodes a tree to a single string.
public String serialize(TreeNode root) {
StringBuilder data = new StringBuilder();
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while(!q.isEmpty()){
TreeNode curr = q.poll();
if(curr == null) data.append("n,");
else {
data.append(curr.val + ",");
q.add(curr.left);
q.add(curr.right);
}
}
return data.toString();
}

// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
String[] values = data.split(",");
if(values[0].equals("n")) return null;
TreeNode root = new TreeNode(Integer.parseInt(values[0]));
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
int i = 1;
while(!q.isEmpty() && i < values.length){
TreeNode curr = q.poll();
curr.left = values[i].equals("n") ? null : new TreeNode(Integer.parseInt(values[i]));
if(i++ < values.length) curr.right = values[i].equals("n") ? null : new TreeNode(Integer.parseInt(values[i]));
if(curr.left != null) q.add(curr.left);
if(curr.right != null) q.add(curr.right);
i++;
}
return root;
}
}

// Your Codec object will be instantiated and called as such:
// Codec ser = new Codec();
// Codec deser = new Codec();
// TreeNode ans = deser.deserialize(ser.serialize(root));
841. Keys and Rooms

841. Keys and Rooms

Question

There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.

When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms.

Given an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i, return true if you can visit all the rooms, or false otherwise.

Solution

BFS,创建一个数组记录房间是否被访问。(用DFS搜素亦可。)

如果钥匙对应的房间已经访问过则跳过。
如果未访问过则记录为已访问并加入队列。

最后遍历一次访问状态,如果有没访问过的房间则返回false。反之返回true。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
int[] visited = new int[rooms.size()];
visited[0] = 1;
Queue<List<Integer>> q = new LinkedList<>();
q.add(rooms.get(0));

while(!q.isEmpty()){
List<Integer> keys = q.poll();
for(int key : keys){
if(visited[key] == 1) continue;
visited[key] = 1;
q.add(rooms.get(key));
}
}

for(int i=1; i<rooms.size(); i++){
if(visited[i] == 0) return false;
}
return true;
}
}

199. Binary Tree Right Side View

Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

BFS搜索。层级遍历各个节点,当节点为该层级最后一个节点时,将其值加入返回列表。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> ret = new ArrayList<>();
if(root == null) return ret;
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
int size = 1;
while(!q.isEmpty()){
for(int i = 0; i < size; i++){
TreeNode curr = q.poll();
if(i == size - 1) ret.add(curr.val);
if(curr.left != null) q.add(curr.left);
if(curr.right != null) q.add(curr.right);
}
size = q.size();
}
return ret;
}
}

103. Binary Tree Zigzag Level Order Traversal

Given the root of a binary tree, return the zigzag level order traversal of its nodes’ values. (i.e., from left to right, then right to left for the next level and alternate between).

BFS搜索,每次遍历挤出整层的节点。
根据真值reverse来判断列表顺序。
当reverse为真,则每次添加元素到列表头。
反之则添加元素到列表尾。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> ret = new ArrayList<>();
if(root == null) return ret;
Deque<TreeNode> q = new LinkedList<>();
q.add(root);
int size = 1;
boolean reverse = false;

while(!q.isEmpty()){
List<Integer> level = new ArrayList<Integer>();
for(int i = 0; i < size; i++){
TreeNode curr = q.poll();
if(reverse){
level.add(0, curr.val);
}
else{
level.add(curr.val);
}
if(curr.left != null) q.add(curr.left);
if(curr.right != null) q.add(curr.right);

}

reverse = !reverse;
ret.add(level);
size = q.size();
}
return ret;
}
}

双端队列,根据真值reverse来判断是取队头还是取队尾。
每层级需要遍历所有的节点。
注意添加节点时也需要根据reverse来决定加入对头还是队尾。
(从一个层级取出时,加入下一个层级元素需要从队列另一边压入。)
同时左右节点的加入顺序也需要调整。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> ret = new ArrayList<>();
if(root == null) return ret;
Deque<TreeNode> dq = new LinkedList<>();
dq.add(root);
int size = 1;
boolean reverse = false;

while(!dq.isEmpty()){
List<Integer> temp = new ArrayList<Integer>();
for(int i = 0; i < size; i++){
if(reverse){
TreeNode curr = dq.removeLast();
if(curr.right != null) dq.offerFirst(curr.right);
if(curr.left != null) dq.offerFirst(curr.left);
temp.add(curr.val);
}
else{
TreeNode curr = dq.removeFirst();
if(curr.left != null) dq.offerLast(curr.left);
if(curr.right != null) dq.offerLast(curr.right);
temp.add(curr.val);
}
}

reverse = !reverse;
ret.add(temp);
size = dq.size();
}
return ret;
}
}

785. Is Graph Bipartite?

There is an undirected graph with n nodes, where each node is numbered between 0 and n - 1. You are given a 2D array graph, where graph[u] is an array of nodes that node u is adjacent to. More formally, for each v in graph[u], there is an undirected edge between node u and node v. The graph has the following properties:

  • There are no self-edges (graph[u] does not contain u).
  • There are no parallel edges (graph[u] does not contain duplicate values).
  • If v is in graph[u], then u is in graph[v] (the graph is undirected).
  • The graph may not be connected, meaning there may be two nodes u and v such that there is no path between them.
    A graph is bipartite if the nodes can be partitioned into two independent sets A and B such that every edge in the graph connects a node in set A and a node in set B.

Return true if and only if it is bipartite.

原题等于问:每个节点与其相连接的节点是否可以颜色不同?
通过BFS搜索,将每一层通过开关flag分组。
创建一个visited数组,记录分组和遍历情况。
当节点被放入错误的分组时,返回false。

注意因为图里的各个节点可能不连接,因此需要遍历对所有节点进行BFS搜索,通过visited的情况进行剪枝。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
public boolean isBipartite(int[][] graph) {
Queue<int[]> q = new LinkedList<>();
int[] visited = new int[graph.length];

for(int i = 0; i < graph.length; i++){
boolean flag = false;
if(graph[i].length == 0 || visited[i] != 0) continue;
q.add(graph[i]);
visited[i] = 1;
int size = 1;

while(!q.isEmpty()){
for(int j = 0; j < size; j++){
int[] node = q.poll();
for(int next : node){
if(visited[next] == 0){
q.add(graph[next]);
}
if(flag){
if(visited[next] == 2) return false;
visited[next] = 1;
}
else{
if(visited[next] == 1) return false;
visited[next] = 2;
}
}
}
flag = !flag;
size = q.size();
}
}
return true;
}
}

1091. Shortest Path in Binary Matrix

Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1.

A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the bottom-right cell (i.e., (n - 1, n - 1)) such that:

All the visited cells of the path are 0.
All the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner).
The length of a clear path is the number of visited cells of this path.

由于不能重复搜索,且需要在搜索时将搜索过的位置改变,因此需要采用BFS逐一层级的搜索。
逐层级搜索并记录层级。最后返回层级+1即可。
(还有更快的优化算法A*)

整体没有改变太多,基本还是方法二那种。启发式函数改为切比雪夫距离距离。
距离计算方法有很多,常用启发式函数有这几种。选择合适的启发式函数有利于速度的提升。这题可以用好几种启发式函数,初学都可以试着都写一下。

曼哈顿距离(Manhattan Distance)
一般只能在四个方向上移动时用(右、左、上、下)

对角线距离(Diagonal Distance):
当我们只允许向八个方向移动时用(国际象棋中的王移动方式那种)

欧几里得距离(Euclidean Distance):
不受限制,允许向任何方向移动时。

切比雪夫距离(Chebyshev Distance):
可参考:[https://leetcode-cn.com/problems/minimum-time-visiting-all-points/solution/fang-wen-suo-you-dian-de-zui-xiao-shi-jian-by-le-2/](LeetCode 1266)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {
public int shortestPathBinaryMatrix(int[][] grid) {
int n = grid[0].length;
int m = grid.length;

Queue<Integer> q = new LinkedList<>();
int count = 0;
q.add(0);
int size = q.size();

while(!q.isEmpty()){
for(int k = 0; k < size; k++){
int curr = q.poll();
int i = curr / n;
int j = curr % n;

if(grid[i][j] ==1) continue;
if(i == m-1 && j == n-1 && grid[i][j] == 0) return count+1;

if(grid[i][j] == 0){
grid[i][j] = 1;
if(i+1<n && j+1<n) q.add((i+1) * n + (j+1));
if(i+1<n && j-1>=0) q.add((i+1) * n + (j-1));
if(i+1<n) q.add((i+1) * n + j);
if(i-1>=0 && j-1>=0) q.add((i-1) * n + (j-1));
if(i-1>=0 && j+1<n) q.add((i-1) * n + (j+1));
if(j+1<n) q.add(i * n + (j+1));
if(j-1>=0) q.add(i * n + (j-1));
if(i-1>=0) q.add((i-1) * n + j);
}
}
size = q.size();
count++;
}
return -1;
}
}

572. Subtree of Another Tree

Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise.

A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node’s descendants. The tree tree could also be considered as a subtree of itself.

帮助方法isEqual,DFS搜索判断两个节点的子节点是否完全相同。
DFS搜索,如果两个根节点的值相等则返回,且调用isEqual方法,如果子节点都相同则返回。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSubtree(TreeNode root, TreeNode subRoot) {
return dfs(root, subRoot) != null;
}

private TreeNode dfs(TreeNode root, TreeNode subRoot){
if(root == null) return null;
if(root.val == subRoot.val && isEqual(root, subRoot)) return root;
if(dfs(root.left, subRoot) != null ) return dfs(root.left, subRoot);
else return dfs(root.right, subRoot);
}

private boolean isEqual(TreeNode root, TreeNode subRoot){
if(root == null || subRoot == null) return root == subRoot;
if(root.val != subRoot.val) return false;
return isEqual(root.left, subRoot.left) && isEqual(root.right, subRoot.right);
}
}

117. Populating Next Pointers in Each Node II

Question

Given a binary tree

1
2
3
4
5
6
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}

Populate each next pointer to point to its next right node. If > there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

Solution

BFS搜索,从右至左将每层节点放入队列。
用一个size记录该层级放入节点的数量,每次循环将size-1,当size归零时放入新一层级的节点。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/*
// Definition for a Node.
class Node {
public int val;
public Node left;
public Node right;
public Node next;

public Node() {}

public Node(int _val) {
val = _val;
}

public Node(int _val, Node _left, Node _right, Node _next) {
val = _val;
left = _left;
right = _right;
next = _next;
}
};
*/

class Solution {
public Node connect(Node root) {
if(root == null) return root;

Queue<Node> q = new LinkedList();
q.add(root);

while(!q.isEmpty()){
int size = q.size();
Node next = null;
while(size > 0){
size--;
Node curr = q.poll();
curr.next = next;
next = curr;
if(curr.right != null) q.add(curr.right);
if(curr.left != null) q.add(curr.left);
}
}
return root;
}
}

104. Maximum Depth of Binary Tree

问题
Given the root of a binary tree, return its maximum depth.

A binary tree’s maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

递归,每次返回左子节点和右子节点中较大的结果+1。
当节点为null时返回0。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
}
}

BFS搜索,每次倾倒出队列里所有的元素并将level+1。
搜索完毕返回level。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
Queue<TreeNode> q = new LinkedList();
q.offer(root);
int level = 0;
while(!q.isEmpty()){
int size = q.size();
for (int i = 0; i < size; i++){
TreeNode curr = q.poll();
if(curr.left!=null){q.offer(curr.left);}
if(curr.right!=null){q.offer(curr.right);}
}
level++;
}
return level;
}
}

102. Binary Tree Level Order Traversal

Question

Given the root of a binary tree, return the level order traversal of its nodes’ values. (i.e., from left to right, level by level).

Solution

BFS搜索,层序遍历,记录每个层级的节点数量size。
在遍历时挤出size个节点,并将其子节点加入队列。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> ret = new ArrayList<>();
if(root == null) return ret;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);

int size = 1;
while(!q.isEmpty()){
List<Integer> list = new ArrayList<>();
TreeNode curr = null;
for(int i = 0; i < size; i++){
curr = q.poll();
if(curr.left != null) q.offer(curr.left);
if(curr.right != null) q.offer(curr.right);
list.add(curr.val);
}
ret.add(list);
size = q.size();
}
return ret;
}
}