38、二叉树的深度
题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度
1、递归法
import java.lang.Math; // 主要是先想清楚:递归基是什么?
public class Solution { // 如何将全局化解题为三节点二叉树解题(平凡的情况)
public int TreeDepth(TreeNode pRoot)
{
if(pRoot == null ){return 0 ;} //递归基:当前节点为空,返回0;
int left = TreeDepth(pRoot.left); //递归左树
int right = TreeDepth(pRoot.right); //递归右树
return Math.max(left, right) + 1; //比较左右树,回溯+1 ;
}
}
2、非递归法(层次遍历)
import java.util.*;
public class Solution {
public int TreeDepth(TreeNode root) {
if(root==null) return 0;
//创建一个辅助队列,可以用arrayList来模拟
ArrayList<TreeNode> queue = new ArrayList<TreeNode>();
int count = 0; //当前层的第几个
int width = 0; //当前层的宽度
int depth = 0; //当前层深度
//将头节点入队列
queue.add(root);
//层次遍历,直到队列中为空
while (!queue.isEmpty()) {
count = 0;//每进入一层,就从当前层的第一个节点开始
width = queue.size(); //获得每一层的宽度
//================当前层遍历==========================
while (count < width) { //遍历当前层的元素,直到计数器大于当前层的宽度
TreeNode cur = queue.remove(0); //队列头出队列,即当前节点
if (cur.left != null) queue.add(cur.left); //若其有左孩子,入队
if (cur.right!=null) queue.add(cur.right); //若其有右孩子,入队
count++; //当前层,每弹出一个(即遍历一个),就将计数器++
}
depth++; //每遍历完一层,深度+1
}
return depth;
}
}
```