forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary_Tree.java
68 lines (58 loc) · 1.65 KB
/
Binary_Tree.java
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
package Binary_Tree;
import java.util.Scanner;
public class Binary_Tree {
private Node root;
private int size;
Scanner s=new Scanner(System.in);
public Binary_Tree(){
root=takeInput(null,false);
}
public Node takeInput(Node parent,Boolean isleftorright){
if(parent==null){
System.out.println("Enter the value of root node");
}
else {
if(isleftorright){
System.out.println("enter the value of left child of "+parent.value);
}
else {
System.out.println("enter the value of right child "+parent.value);
}
}
int value=s.nextInt();
Node node=new Node(value,null,null);
boolean choice;
System.out.println("Do you have left child of "+node.value);
choice=s.nextBoolean();
if(choice){
node.left=takeInput(node,true);
}
System.out.println("Do you have right child of "+node.value);
choice=s.nextBoolean();
if(choice){
node.right=takeInput(node,false);
}
return node;
}
public void preOrder() {
preOrder(root);
}
private void preOrder(Node node) {
if (node == null) {
return;
}
System.out.print(node.value + ",");
preOrder(node.left);
preOrder(node.right);
}
private class Node{
private Node left;
private Node right;
private int value;
private Node(int value, Node left, Node right){
this.value=value;
this.left=left;
this.right=right;
}
}
}