目录
104.二叉树的最大深度
题目
给定一个二叉树 root
,返回其最大深度。
二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。
示例 1:
输入:root = [3,9,20,null,null,15,7] 输出:3
代码(后序递归)
class Solution {
public int maxDepth(TreeNode root) {
//后序递归,初始深度=0
int depth = postOrder(root);
return depth;
}
//后序遍历计算深度
public int postOrder(TreeNode root){
//终止条件
if(root == null){
return 0;
}
//遍历左子树,left是左子树深度
int left = postOrder(root.left);
//遍历右子树,right是右子树深度
int right = postOrder(root.right);
return left > right ? left+1 : right+1;
}
}
代码(层序迭代)
class Solution {
public int maxDepth(TreeNode root) {
//层序迭代
Queue<TreeNode> que = new ArrayDeque<>();
//树为空,深度=0
if(root == null){
return 0;
}
//初始深度=0
int depth = 0;
//根节点入队
que.offer(root);
while(!que.isEmpty()){
int size = que.size();
//深度+1
depth++;
//处理当前层的所有节点
while(size-- > 0){
TreeNode cur = que.poll();
if(cur.left != null){
que.offer(cur.left);
}
if(cur.right != null){
que.offer(cur.right);
}
}
}
return depth;
}
}
559.N叉树的最大深度
题目
给定一个 N 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
N 叉树输入按层序遍历序列化表示,每组子节点由空值分隔(请参见示例)。
示例 1:
输入:root = [1,null,3,2,4,null,5,6] 输出:3
代码(后序递归)
class Solution {
public int maxDepth(Node root) {
//后序递归,初始深度=0
int depth = postOrder(root);
return depth;
}
//后序遍历计算深度
public int postOrder(Node root){
//终止条件
if(root == null){
return 0;
}
//单层逻辑
int depth = 0;
//如果root有孩子节点
if(root.children != null){
//遍历每个孩子节点,获取每个孩子的最大高度
for(Node child : root.children){
depth = Math.max(depth,postOrder(child));
}
}
return depth + 1; //孩子高度+中间节点
}
}
代码(层序迭代)
class Solution {
public int maxDepth(Node root) {
//层序迭代计算最大深度
Queue<Node> que = new ArrayDeque<>();
if(root == null){
return 0;
}
int depth = 0; //初始深度为0
que.offer(root);
while(!que.isEmpty()){
int size = que.size();
depth++; //深度+1
while(size-- > 0){
Node cur = que.poll(); //这一层节点出队
//出队的节点,孩子全部入队
if(cur.children != null){
for(Node child : cur.children){
que.offer(child);
}
}
}
}
return depth;
}
}
111.二叉树的最小深度
题目
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
示例 1:
输入:root = [3,9,20,null,null,15,7] 输出:2
代码(后序递归)
class Solution {
public int minDepth(TreeNode root) {
int result = postOrder(root);
return result;
}
public int postOrder(TreeNode root){
//终止条件
if(root == null){
return 0;
}
//单层逻辑
int left = postOrder(root.left); //计算左子树深度
int right = postOrder(root.right); //计算右子树深度
//如果左子树为空,深度为右+1
if(root.left == null){
return right + 1;
}
//如果右子树为空,深度为左+1
if(root.right == null){
return left + 1;
}
//如果左右子树都非空,深度为左右中更小的深度+1
return Math.min(left,right) + 1;
}
}
代码(层序迭代)
class Solution {
public int minDepth(TreeNode root) {
//层序迭代
Queue<TreeNode> que = new ArrayDeque<>();
//树为空,深度=0
if(root == null){
return 0;
}
//初始深度=0
int depth = 0;
//根节点入队
que.offer(root);
while(!que.isEmpty()){
int size = que.size();
//深度+1
depth++;
//处理当前层的所有节点
while(size-- > 0){
TreeNode cur = que.poll();
//如果cur是叶子节点,代表已经找到最小深度了
if(cur.left == null && cur.right == null){
return depth; //可以直接结束层序遍历
}
if(cur.left != null){
que.offer(cur.left);
}
if(cur.right != null){
que.offer(cur.right);
}
}
}
return depth;
}
}