二叉树的深度
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
简单二叉树类
public class TreeNode{
public int val = 0;
public TreeNode left = null;
public TreeNode right = right;
public TreeNode(int val){
this.val = val;
}
}
方法一:递归法(分治法)
求一个规模为n的问题,可以先求左边规模大约为n/2的问题,然后求右边n/2的问题,最后合并左边,右边的解,从而求的最终解。具体可以参考归并排序。
public class Solution{
public int treeDepth(TreeNode root){
if(root == null){
return 0;
}
left = treeDepth(root.left);//递归计算左子树的深度;
right = treeDepth(root.right);//递归计算右子树的深度;
return Math.max(left, right) + 1;//选取左右子树深度的最大值,算上根节点,所以深度+1;
}
}
方法二:非递归方法(层次遍历)
利用队列,count是当前的节点,nextcount是当前深度总的节点(总是遍历的当前深度的最后一个节点,深度才+1)
import java.util.LinkedList;
public int treeDepth(TreeNode root){
if(root == null){
return 0;
}
Queue <TreeNode> q = new LinkedList <TreeNode>();//声明队列q;
q.add(root);//将二叉树添加到队列中;
int d = 0, count = 0, nextcount = q.size();//count是当前节点的数量,nextcount是当前深度 节点的数量;
while(q.size() != 0){
TreeNode t = q.poll();//将队列中的二叉树放入变量t中;
count++;
if(t.left != null){
q.add(t.left);
}
if(t.right != null){
q.add(t.right);
}
if(count == nextcount){//这个很关键,用于判断当前深度是否已经遍历到最后一个节点。一定要自己画图走一遍!!!
d++;
count = 0;
nextcount = q.size();
}
}
return d;
}
总结
递归确实很香,但是不用递归的方法有时候也很重要。深度遍历,广度遍历非常重要!!!