-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathremovetheleaves(Binary Tree)
106 lines (79 loc) · 1.84 KB
/
removetheleaves(Binary Tree)
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import java.util.*;
public class Main {
static Scanner scn = new Scanner(System.in);
public static void main(String[] args) {
Main m = new Main();
BinaryTree bt = m.new BinaryTree();
bt.removeLeaves();
bt.display();
}
private class BinaryTree {
private class Node {
int data;
Node left;
Node right;
}
private Node root;
private int size;
public BinaryTree() {
this.root = this.takeInput(null, false);
}
public Node takeInput(Node parent, boolean ilc) {
int cdata = scn.nextInt();
Node child = new Node();
child.data = cdata;
this.size++;
// left
boolean hlc = scn.nextBoolean();
if (hlc) {
child.left = this.takeInput(child, true);
}
// right
boolean hrc = scn.nextBoolean();
if (hrc) {
child.right = this.takeInput(child, false);
}
// return
return child;
}
public void display() {
this.display(this.root);
}
private void display(Node node) {
if (node == null) {
return;
}
String str = "";
if (node.left != null) {
str += node.left.data;
} else {
str += "END";
}
str += " => " + node.data + " <= ";
if (node.right != null) {
str += node.right.data;
} else {
str += "END";
}
System.out.println(str);
this.display(node.left);
this.display(node.right);
}
public void removeLeaves() {
this.removeLeaves(this.root, null, 0);
}
private void removeLeaves(Node root, Node parent,int direction) {
if(root != null && root.left == null && root.right == null){
if(direction == 0){
parent.left = null;
}else{
parent.right = null;
}
}
if(root != null && (root.left != null || root.right != null)){
removeLeaves(root.left, root, 0);
removeLeaves(root.right, root, 1);
}
}
}
}