题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
方法一:非递归 (层次遍历)
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
//用层次遍历求二叉树的深度
import java.util.LinkedList;
public class Solution {
public int TreeDepth(TreeNode root) {
if(root==null){
return 0;
}
int height=0;
//用linkedList来存储每层数元素
LinkedList<TreeNode> list = new LinkedList<>();
list.add(root);
while(list.size()>0){
//第一步是用count变量来存储每层元素的个数
int count=list.size();
//遍历每层元素
for(int i=0;i<count;i++){
TreeNode head = list.removeFirst();
if(head.left!=null){
list.add(head.left);
}
if(head.right!=null){
list.add(head.right);
}
}
height++;
}
return height;
}
}
方法二:递归
import java.lang.Math;
public class Solution {
public int TreeDepth(TreeNode pRoot)
{
if(pRoot == null){
return 0;
}
int left = TreeDepth(pRoot.left);
int right = TreeDepth(pRoot.right);
return Math.max(left, right) + 1;
}
}