题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
方法一:层次遍历
import java.util.Queue;
import java.util.LinkedList;
public class Solution {
public int TreeDepth(TreeNode root) {
if(root==null) return 0;
else{
Queue<TreeNode> q=new LinkedList<TreeNode>();
int higth=0;
q.add(root);
while(!q.isEmpty())
{
int length=q.size();
++higth;
for(int i=0;i<length;i++)
{
TreeNode tem=q.poll();
if(tem.left!=null) q.add(tem.left);
if(tem.right!=null) q.add(tem.right);
}
}
return higth;
}
}
}
方法2:递归。
public class Solution {
public int TreeDepth(TreeNode root) {
if(root==null) return 0;
int h1=TreeDepth(root.left); //左子树长度
int h2=TreeDepth(root.right); //右子树长度
return Math.max(h1,h2)+1; //算上根节点长度
}
}