public class Solution {
方法一:递归解法
public int TreeDepth(TreeNode root) {
if(root==null)
return 0;
int lval = TreeDepth(root.left); //先遍历左子树
int rval = TreeDepth(root.right);//接着遍历右子树
return Math.max(lval,rval)+1;
}
//方法二:非递归解法(层次遍历,用队列结构)
public int TreeDepth(TreeNode root) {
if(root==null)
return 0;
Queue<TreeNode> q = new LinkedList<>();
int depth = 0;//深度初始化为0
q.add(root);//跟结点入列
while(!q.isEmpty()){ //当队列不为空
int curSize = q.size(); //当前层的结点数目
while(curSize-->0){
//依次将各结点的左右子结点添加到队列
TreeNode cur = q.poll();
//左结点入列
if(cur.left!=null)
q.add(cur.left);
//右结点入列
if(cur.right!=null)
q.add(cur.right);
//一个结点完成任务,curSize-1,括号里已经减了,这里就不用再减
}
depth++;
}
return depth;
}
}