解题思路1:
使用递归方法
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public int TreeDepth(TreeNode root) {
if(root == null){
return 0;
}
//左子树深度
int leftDeep = 1;
//右子树深度
int rightDeep = 1;
//判断左子树
if(root.left != null){
leftDeep = TreeDepth(root.left) + 1;
}
//判断右子树
if(root.right != null){
rightDeep = TreeDepth(root.right) + 1;
}
//返回最大值
return leftDeep >= rightDeep ? leftDeep: rightDeep;
}
}
解题思路2:
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.Queue;
import java.util.LinkedList;
public class Solution {
public int TreeDepth(TreeNode root) {
if(root == null){
return 0;
}
Queue<TreeNode> q = new LinkedList<TreeNode>();
//深度
int depth = 0;
//已取出子节点数目
int count = 0;
//某一层的节点数,初始值为1,因为根节点只有1个节点
int allCount = 1;
//添加到队列中
q.add(root);
while(q.size() > 0){
//取出第一个
TreeNode top = q.poll();
count++;
if(top.left != null){
q.add(top.left);
}
if(top.right != null){
q.add(top.right);
}
//当前层已经取出完了
if(count == allCount){
//获得下一层节点数
allCount = q.size();
//清零
count = 0;
//深度加1
depth++;
}
}
return depth;
}
}