A very easy and neat way to compute height of tree is using recursive function.
private int height(Node node) {
if (null == node)
return 0;
else {
return (1 + Math.max(height(node.left), height(node.right)));
}
}
public int height() {
return height(root);
}
As an alternative, we can use iterative way to compute it.
Here, I used the breadth first to compute height of a tree.
public int iterativeHeight() {
int rvl = 0;
int numNode = 0;
Node node = root;
// queue
LinkedList> que = new LinkedList();
que.addLast(node);
numNode = 1; // in root level
while (!que.isEmpty()) {
rvl++;
int localNum = 0; //record how many node added in level
for (; numNode > 0; numNode--) {
node = que.removeFirst();
if (node.right != null) {
que.addLast(node.right);
localNum++;
}
if (node.left != null) {
que.addLast(node.left);
localNum++;
}
}
numNode = localNum;
}
return rvl;
}
No comments:
Post a Comment