forked from JFulgoni/Java-Practice
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTreeNode.java
More file actions
75 lines (68 loc) · 1.5 KB
/
Copy pathTreeNode.java
File metadata and controls
75 lines (68 loc) · 1.5 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
package john_test;
import java.util.LinkedList;
import java.util.Queue;
public class TreeNode {
public int val;
public TreeNode left = null;
public TreeNode right = null;
public TreeNode(int x){
this.val = x;
}
public void setLeft(TreeNode next){
this.left = next;
}
public void setRight(TreeNode next){
this.right = next;
}
/*
* got this from online somewhere
*/
public boolean add(int value) {
if (value == this.val)
return false;
else if (value <this.val) {
if (left == null) {
left = new TreeNode(value);
return true;
} else
return left.add(value);
} else if (value > this.val) {
if (right == null) {
right = new TreeNode(value);
return true;
} else
return right.add(value);
}
return false;
}
// this is all pure crap
// public String toString(){
// return treeString(this);
// }
// public String treeString(TreeNode root){
// if(root == null){
// return "";
// }
// return Integer.toString(root.val) + '\n' + treeString(root.left) + ',' + treeString(root.right);
// }
/*
* got this from stack overflow as well
*/
public String byLevel(){
Queue<TreeNode> level = new LinkedList<TreeNode>();
level.add(this);
StringBuilder sb = new StringBuilder();
while(!level.isEmpty()){
TreeNode node = level.poll();
sb.append(node.val + " ");
//System.out.print(node.val + " ");
if(node.left != null){
level.add(node.left);
}
if(node.right!= null){
level.add(node.right);
}
}
return sb.toString();
}
}