forked from krahets/LeetCode-Book
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTreeNode.java
More file actions
80 lines (74 loc) · 2.01 KB
/
TreeNode.java
File metadata and controls
80 lines (74 loc) · 2.01 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package include;
import java.util.*;
/**
* Definition for a binary tree node.
*/
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) {
val = x;
}
/**
* Generate a binary tree with an array
* @param arr
* @return
*/
public static TreeNode arrToTree(Integer[] arr) {
TreeNode root = new TreeNode(arr[0]);
Queue<TreeNode> queue = new LinkedList<TreeNode>() {{ add(root); }};
int i = 1;
while(!queue.isEmpty()) {
TreeNode node = queue.poll();
if(arr[i] != null) {
node.left = new TreeNode(arr[i]);
queue.add(node.left);
}
i++;
if(arr[i] != null) {
node.right = new TreeNode(arr[i]);
queue.add(node.right);
}
i++;
}
return root;
}
/**
* Serialize a binary tree to a list
* @param root
* @return
*/
public static List<Integer> treeToList(TreeNode root) {
List<Integer> list = new ArrayList<>();
if(root == null) return list;
Queue<TreeNode> queue = new LinkedList<TreeNode>() {{ add(root); }};
while(!queue.isEmpty()) {
TreeNode node = queue.poll();
if(node != null) {
list.add(node.val);
queue.add(node.left);
queue.add(node.right);
}
else {
list.add(null);
}
}
return list;
}
/**
* Get a tree node with specific value in a binary tree
* @param root
* @param val
* @return
*/
public static TreeNode getTreeNode(TreeNode root, int val) {
if (root == null)
return null;
if (root.val == val)
return root;
TreeNode left = getTreeNode(root.left, val);
TreeNode right = getTreeNode(root.right, val);
return left != null ? left : right;
}
}