-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHeightOfBinaryTree.java
42 lines (36 loc) · 1.23 KB
/
HeightOfBinaryTree.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
package com.anudev.ds.trees;
import java.util.LinkedList;
import java.util.Queue;
public class HeightOfBinaryTree {
public static int heightOfBinaryTreeRecursively(Node node) {
if (node == null) {
return 0;
}
int leftSubtreeMaxHeight = heightOfBinaryTreeRecursively(node.getLeftNode());
int rightSubtreeMaxHeight = heightOfBinaryTreeRecursively(node.getRightNode());
return 1 + Math.max(leftSubtreeMaxHeight, rightSubtreeMaxHeight);
}
public static int heightOfBinaryTreeNonRecursively(Node node) {
int height = 0;
Queue<Node> queue = new LinkedList<>();
queue.add(node);
queue.add(null);
while (!queue.isEmpty()) {
Node queueNode = queue.poll();
if (queueNode == null) {
if (!queue.isEmpty()) {
queue.add(null);
}
height++;
} else {
if (queueNode.getLeftNode() != null) {
queue.add(queueNode.getLeftNode());
}
if (queueNode.getRightNode() != null) {
queue.add(queueNode.getRightNode());
}
}
}
return height;
}
}