forked from javadev/LeetCode-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTreeNode.java
More file actions
59 lines (53 loc) · 1.64 KB
/
TreeNode.java
File metadata and controls
59 lines (53 loc) · 1.64 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
package com_github_leetcode;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
@SuppressWarnings("java:S1104")
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val) {
this.val = val;
}
public TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
public static TreeNode create(List<Integer> treeValues) {
TreeNode root = treeValues.isEmpty() ? null : new TreeNode(treeValues.get(0));
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int i = 1;
while (i < treeValues.size()) {
TreeNode curr = queue.poll();
if (treeValues.get(i) != null) {
curr.left = new TreeNode(treeValues.get(i));
queue.offer(curr.left);
}
if (++i < treeValues.size() && treeValues.get(i) != null) {
curr.right = new TreeNode(treeValues.get(i));
queue.offer(curr.right);
}
i++;
}
return root;
}
public String toString() {
if (left == null && right == null) {
return "" + val;
} else {
String root = "" + val;
String leftValue = "null";
String rightValue = "null";
if (left != null) {
leftValue = left.toString();
}
if (right != null) {
rightValue = right.toString();
}
return root + "," + leftValue + "," + rightValue;
}
}
}