-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBSTIterativeHeight.java
More file actions
86 lines (68 loc) · 1.87 KB
/
BSTIterativeHeight.java
File metadata and controls
86 lines (68 loc) · 1.87 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.*;
import java.lang.*;
import java.io.*;
import java.util.LinkedList;
import java.util.Queue;
// A binary tree node
class Node
{
int data;
Node left, right;
Node(int item)
{
data = item;
left = right;
}
}
class BinaryTree
{
Node root;
// Iterative method to find height of Bianry Tree
int treeHeight(Node node)
{
// Base Case
if (node == null)
return 0;
// Create an empty queue for level order tarversal
Queue<Node> q = new LinkedList();
// Enqueue Root and initialize height
q.add(node);
int height = 0;
while (1 == 1)
{
// nodeCount (queue size) indicates number of nodes
// at current lelvel.
int nodeCount = q.size();
if (nodeCount == 0)
return height;
height++;
// Dequeue all nodes of current level and Enqueue all
// nodes of next level
while (nodeCount > 0)
{
Node newnode = q.peek();
q.remove();
if (newnode.left != null)
q.add(newnode.left);
if (newnode.right != null)
q.add(newnode.right);
nodeCount--;
}
}
}
// Driver program to test above functions
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
// Let us create a binary tree shown in above diagram
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
System.out.println("Height of tree is " + tree.treeHeight(tree.root));
}
}
/* OUTPUT
Height of tree is 3
*/