题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
(1)二叉树深度使用递归
public class Solution {
public int TreeDepth(TreeNode root) {
int count=0;
if(root==null){
return 0;
}
int left=TreeDepth(root.left);
int right = TreeDepth(root.right);
return left>right?left+1:right+1;
}
}
(2) 使用层次遍历,没遍历一层,树的深度就加1
public int TreeDepth(TreeNode root) {
//使用层次遍历,没遍历一层树的高度就加1
if(root==null){
return 0;
}
ArrayList<TreeNode> list=new ArrayList<TreeNode>();
list.add(root);
int count=0;
while(list.size()!=0){
count++;
for(int i=0;i<list.size();i++){
TreeNode node=list.remove(0);
if(node.left!=null){
list.add(node.left);
}
if(node.right!=null){
list.add(node.right);
}
}
}
return count;
}