记录几种获取二叉树高度的实现方法,代码仅java实现。
二叉树结构定义为:
public class Node {
char val;
Node left;
Node right;
public Node(){}
public Node(int val) {
this.val = val;
}
}
递归
public static int calTreeHeight(Node root) {
if (root == null)
return 0;
return Math.max(calTreeHeight(root.left), calTreeHeight(root.right)) + 1;
}
非递归
基于按层遍历的思想
public static int calTreeHeight(Node root) {
if (root == null)
return 0;
Queue<Node> nodes = new LinkedList<>();
nodes.offer(root);
int visitedNum = 0;
int enQueueNum = 1;
int levelNodeNum = 1;
int height = 0;
while(!nodes.isEmpty()) {
Node node = nodes.poll();
visitedNum++;
if (node.left != null) {
nodes.offer(node.left);
enQueueNum++;
}
if (node.right != null) {
nodes.offer(node.right);
enQueueNum++;
}
if (visitedNum == levelNodeNum) {
levelNodeNum = enQueueNum;
height++;
}
}
return height;
}
基于后序遍历思想
public static int calTreeHeight(Node root) {
int height = 0;
Stack<Node> nodes = new Stack<>();
Stack<Integer> tag = new Stack<>();
while(root != null || !nodes.isEmpty()) {
// 先遍历左孩子
while(root != null) {
nodes.push(root);
tag.push(0);
root = root.left;
}
if (tag.peek() == 1) {
height = Math.max(height, nodes.size());
nodes.pop();
tag.pop();
root = null;
} else {
root = nodes.peek();
root = root.right;
tag.pop();
tag.push(1);
}
}
return height;
}