-
Notifications
You must be signed in to change notification settings - Fork 0
/
Print middle level of perfect binary tree without finding height
69 lines (62 loc) · 1.39 KB
/
Print middle level of perfect binary tree without finding height
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
// Tree node definition
class Node
{
public int key;
public Node left;
public Node right;
public Node(int val)
{
this.left = null;
this.right = null;
this.key = val;
}
}
public class PrintMiddle
{
// Takes two parameters - same initially and
// calls recursively
private static void printMiddleLevelUtil(Node a,
Node b)
{
// Base case e
if (a == null || b == null)
return;
// Fast pointer has reached the leaf so print
// value at slow pointer
if ((b.left == null) && (b.right == null))
{
System.out.print(a.key + " ");
return;
}
// Recursive call
// root.left.left and root.left.right will
// print same value
// root.right.left and root.right.right
// will print same value
// So we use any one of the condition
printMiddleLevelUtil(a.left, b.left.left);
printMiddleLevelUtil(a.right, b.left.left);
}
// Main printing method that take a Tree as input
public static void printMiddleLevel(Node node)
{
printMiddleLevelUtil(node, node);
}
public static void main(String[] args)
{
Node n1 = new Node(1);
Node n2 = new Node(2);
Node n3 = new Node(3);
Node n4 = new Node(4);
Node n5 = new Node(5);
Node n6 = new Node(6);
Node n7 = new Node(7);
n2.left = n4;
n2.right = n5;
n3.left = n6;
n3.right = n7;
n1.left = n2;
n1.right = n3;
printMiddleLevel(n1);
}
}