求二叉树高度的思路非常简单,类似于二叉树的层次遍历。用一个队列来保存二叉树某一层的结点,判断此队列是否为空,若为空,说明上一层没有子结点,即可结束程序;否则,先得到此队列的长度,依次将上层结点出队列,同时将每个结点的左右孩子(如果有)入队,重复此过程即可。
import java.util.*;
/*结点类
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
*/
public class Solution {
public int maxDepth(TreeNode root) {
int depth=0;
if(root == null)
return 0;
LinkedList list = new LinkedList();
//根结点入队,初始化队列
list.offer(root);
//每一次循环结束后,队列里所有结点同属同一层
while(list.size() != 0){
//队列不为空,则高度加一
depth++;
//本层结点个数
int size = list.size();
//将本层结点依次出队并将孩子入队得到下一层的所有结点
for(int i=0; i<size; i++){
TreeNode e = (TreeNode)list.poll();
if(e.left!=null)
list.offer(e.left);
if(e.right!=null)
list.offer(e.right);
}
}
return depth;
}
}
递归方式:
public int maxDepth(TreeNode root){
if(root==null)
return 0;
int lDepth = maxDepth(root.left);
int rDepth = maxDepth(root.right);
return 1+(lDepth>rDepth?lDepth:rDepth);
}