Skip to content

Commit cd111ed

Browse files
committed
add print structure in treeNode
1 parent 5728b0f commit cd111ed

File tree

1 file changed

+82
-2
lines changed

1 file changed

+82
-2
lines changed
Lines changed: 82 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,91 @@
11
package common;
22

3+
import java.util.ArrayList;
4+
import java.util.LinkedList;
5+
import java.util.List;
6+
37
public class TreeNode {
48
public int val;
59
public TreeNode left;
610
public TreeNode right;
7-
public TreeNode(int x) {
8-
val = x;
11+
public TreeNode() { }
12+
public TreeNode(int val) {
13+
this.val = val;
14+
}
15+
16+
public TreeNode(int val, TreeNode left, TreeNode right) {
17+
this.val = val;
18+
this.left = left;
19+
this.right = right;
920
}
1021

22+
@Override
23+
public String toString() {
24+
if (this == null) {
25+
return "null";
26+
}
27+
28+
String result = "";
29+
List<String> row = null;
30+
List<List<String>> list = new ArrayList<List<String>>();
31+
32+
LinkedList<TreeNode> rowNode = new LinkedList<>();
33+
rowNode.add(this);
34+
while (!rowNode.isEmpty()) {
35+
int rowSize = rowNode.size();
36+
row = new ArrayList<String>();
37+
38+
int rowCount = rowSize;
39+
int nullCount = 0;
40+
while (rowSize > 0) {
41+
TreeNode current = rowNode.pop();
42+
if (current == null) {
43+
row.add("null");
44+
nullCount++;
45+
} else {
46+
row.add(Integer.toString(current.val));
47+
}
48+
49+
if (current == null || current.left == null) {
50+
rowNode.add(null);
51+
} else {
52+
rowNode.add(current.left);
53+
}
54+
if (current == null || current.right == null) {
55+
rowNode.add(null);
56+
} else {
57+
rowNode.add(current.right);
58+
}
59+
60+
rowSize--;
61+
}
62+
63+
if (nullCount == rowCount) {
64+
break;
65+
}
66+
67+
list.add(row);
68+
}
69+
70+
// print data
71+
String blank = " ";
72+
for (int i = 0; i < list.size(); i ++) {
73+
for (int j = i; j < list.size(); j++) {
74+
// print blank
75+
System.out.print(blank);
76+
}
77+
List<String> rowList = list.get(i);
78+
for (int k = 0; k < rowList.size(); k++) {
79+
System.out.print(rowList.get(k));
80+
System.out.print(blank);
81+
}
82+
83+
System.out.println();
84+
}
85+
86+
87+
//return Arrays.toString(list.toArray());
88+
89+
return super.toString();
90+
}
1191
}

0 commit comments

Comments
 (0)