-
Notifications
You must be signed in to change notification settings - Fork 28
/
BinaryTree.Java
130 lines (127 loc) · 2.99 KB
/
BinaryTree.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
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
import java.util.LinkedList;
import java.util.Queue;
public class DeleteNode
{
// A binary tree node has key, pointer to
// left child and a pointer to right child
static class Node
{
int key;
Node left, right;
// Constructor
Node(int key)
{
this.key = key;
left = null;
right = null;
}
}
static Node root;
static Node temp = root;
// Inorder traversal of a binary tree
static void inorder(Node temp)
{
if (temp == null)
return;
inorder(temp.left);
System.out.print(temp.key + " ");
inorder(temp.right);
}
// Function to delete deepest
// element in binary tree
static void deleteDeepest(Node root, Node delNode)
{
Queue<Node> q = new LinkedList<Node>();
q.add(root);
Node temp = null;
// Do level order traversal until last node
while (!q.isEmpty())
{
temp = q.peek();
q.remove();
if (temp == delNode)
{
temp = null;
return;
}
if (temp.right!=null)
{
if (temp.right == delNode)
{
temp.right = null;
return;
}
else
q.add(temp.right);
}
if (temp.left != null)
{
if (temp.left == delNode)
{
temp.left = null;
return;
}
else
q.add(temp.left);
}
}
}
// Function to delete given element
// in binary tree
static void delete(Node root, int key)
{
if (root == null)
return;
if (root.left == null &&
root.right == null)
{
if (root.key == key)
{
root=null;
return;
}
else
return;
}
Queue<Node> q = new LinkedList<Node>();
q.add(root);
Node temp = null, keyNode = null;
// Do level order traversal until
// we find key and last node.
while (!q.isEmpty())
{
temp = q.peek();
q.remove();
if (temp.key == key)
keyNode = temp;
if (temp.left != null)
q.add(temp.left);
if (temp.right != null)
q.add(temp.right);
}
if (keyNode != null)
{
int x = temp.key;
deleteDeepest(root, temp);
keyNode.key = x;
}
}
// Driver code
public static void main(String args[])
{
root = new Node(10);
root.left = new Node(11);
root.left.left = new Node(7);
root.left.right = new Node(12);
root.right = new Node(9);
root.right.left = new Node(15);
root.right.right = new Node(8);
System.out.print("Inorder traversal before deletion: ");
inorder(root);
//node to delete
int key = 7;
delete(root, key);
System.out.print("\nInorder traversal after deletion: ");
inorder(root);
}
}