二叉树的深度
二叉树的根节点为第一层,根节点的子节点为第二层,以此类推,最大层数即为二叉树的深度
如下图所示二叉树深度为3
求二叉树深度
二叉树节点定义如下:
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
求二叉树的深度可用两种方法:深度优先遍历和广度优先遍历
1. 广度优先遍历(BFS)
使用BFS对二叉树进行层次遍历,每遍历一层树的深度加1,遍历完整个二叉树时即可得到二叉树的深度。
public int TreeDepth(TreeNode root) {
if(root == null){
return 0;
}
int deep = 0;
// 队列存储每一层的节点
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
// 本层遍历节点个数
int size = queue.size();
for(int i = 0;i < size;i++){
TreeNode top = queue.poll();
//把当前节点的左右子节点加入列表
if(top.left != null){
queue.offer(top.left);
}
if(top.right != null){
queue.offer(top.right);
}
}
// 遍历完一层,深度加一
deep++;
}
return deep;
}
2. 深度优先遍历(DFS)
使用DFS递归遍历可求出每个叶子节点的深度,最大的值就是二叉树的深度
public int TreeDepth(TreeNode root) {
if(root == null){
return 0;
}
// 如果有左右子节点,则结果是左右子树中最大的值加1,即加上父节点
if(root.left != null && root.right != null){
return 1 + Math.max(TreeDepth(root.left),TreeDepth(root.right));
}else if(root.left != null){
return 1 + TreeDepth(root.left); //只有左节点,则深度为左子树深度加1
}else if(root.right != null){
return 1 + TreeDepth(root.right);//只有右节点,则深度为右子树深度加1
}else{
return 1; //没有孩子节点,深度为1
}
}