-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinTree.java
More file actions
86 lines (65 loc) · 1.46 KB
/
Copy pathBinTree.java
File metadata and controls
86 lines (65 loc) · 1.46 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
81
82
83
84
85
86
import java.util.ArrayList;
public class BinTree {
BinTree left;
String name;
BinTree right;
public static void main(String[] args) {
// TODO Auto-generated method stub
BinTree tree = new BinTree(new BinTree(null, null, "1"), new BinTree(null, null,"2"), "3" );
tree.printTree(tree);
}
public BinTree( BinTree left , BinTree right, String name){
this.left = left;
this.right=right;
this.name =name;
}
public void printTreeHelper(ArrayList<BinTree> treelist){
while( treelist.size()!=0){
ArrayList<BinTree> list = new ArrayList<BinTree>();
for ( BinTree tree : treelist){
System.out.print(tree.name + " ");
//add children
if( tree.left!=null || tree.right!=null){
list.add(tree.left);
list.add(tree.right);
}
}
treelist = list;
System.out.println();
}
return;
}
public void printTree( BinTree tree){
ArrayList<BinTree> list = new ArrayList<BinTree >();
list.add(tree);
printTreeHelper(list);
}
/*
* Find the depth of a binary tree
*
*
*/
public int depth ( BinTree tree){
int x = 1;
while( tree.left != null){
tree= tree.left;
x++;
}
return x;
}
/*Print all the leaves in a tree
* in order of left to right
* Facebook interview Question
*
*
*/
public void printLeaves( BinTree node){
if( node.left == null){
System.out.println(node.name);
}
else{
printLeaves(node.left);
printLeaves(node.right);
}
}
}