描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
示例1
输入:
{1,2,3,4,5,#,6,#,#,7}
复制
返回值:
4
一、递归
public class Solution {
public int TreeDepth(TreeNode root) {
if (root==null)
return 0;
int left=TreeDepth(root.left);
int right=TreeDepth(root.right);
return Math.max(left,right)+1;
}
}
二、层序遍历
import java.util.*;
public class Solution {
public int TreeDepth(TreeNode root) {
if (root==null)
{return 0;}
//创建一个队列
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
//记录每一层元素个数
int count = 0;
//记录层数,树的深度
int res = 0;
while(!queue.isEmpty()){
//每一层的个数
int size = queue.size();
while(size-->0){
TreeNode cur = queue.poll();
if (cur.left != null)
queue.add(cur.left);
if (cur.right !=null)
queue.add(cur.right);
}
res++;
}
return res;
}
}
- Queue:队列是先入先出的数据结构。
- Queue接口与List、Set同一级别,都是继承了Collection接口。LinkedList实现了Deque接口
- add:添加一个元素,如果队列已满,抛出一个IIIegaISlabEepeplian异常
- remove:移除并返回队列头部的元素,如果队列为空,则抛出一个NoSuchElementException异常
- element :返回队列头部的元素,如果队列为空,则抛出一个NoSuchElementException异常
- offer:添加一个元素并返回true,如果队列已满,则返回false
- poll:移除并返问队列头部的元素,如果队列为空,则返回null
- peek:返回队列头部的元素,如果队列为空,则返回null
- put:添加一个元素,如果队列满,则阻塞
- take:移除并返回队列头部的元素,如果队列为空,则阻塞