题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
思路分析
- 思路一,用递归做。返回1+左右子树中最大的高度。到达树叶结点返回0。
- 思路二,用非递归,层次遍历做。利用辅助队列,将头节点入队列,当队列不空时队列出结点,判断是否为空,空则继续,不空则左右子节点入队列,循环。
注:也可以判断左右子节点不空再入队列。所以我的写法最后需要将高度-1。
注:层次遍历,可以求高度,也可以求多少层的第多少个结点。
代码实现
/**
* 递归版本
*
* @param root
* @return
*/
public static int treeDepth1(TreeNode root) {
if (root == null) {
return 0;
}
return 1 + Math.max(treeDepth1(root.left), treeDepth1(root.right));
}
/**
* 非递归方法,用层次遍历获得树的高度
*
* @param root
* @return
*/
public static int treeDepth2(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
int height = 0;
queue.offer(root);
while (!queue.isEmpty()) {
int count = queue.size();
while (count-- > 0) {
TreeNode node = queue.poll();
if (node == null) {
continue;
}
queue.offer(node.left);
queue.offer(node.right);
}
height++;
}
return height - 1;
}