当前位置:网站首页>Leetcode刷题——一些用层次遍历解决的问题(111. 二叉树的最小深度、104. 二叉树的最大深度、226. 翻转二叉树、剑指 Offer 27. 二叉树的镜像)
Leetcode刷题——一些用层次遍历解决的问题(111. 二叉树的最小深度、104. 二叉树的最大深度、226. 翻转二叉树、剑指 Offer 27. 二叉树的镜像)
2022-08-03 05:20:00 【lonelyMangoo】
这几道题都是用层次遍历解决的,二叉树遍历记录过二叉树的遍历。
111. 二叉树的最小深度
111. 二叉树的最小深度
最小深度就是从第一层开始往下找,找到第一个叶子结点,就是最小深度
public int minDepth(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
if (root==null) return 0;
int minDepth = 0;
while (!queue.isEmpty()){
int len = queue.size()-1;
minDepth++;
while (len-->=0){
TreeNode peek = queue.poll();
if(peek.left==null && peek.right==null) return minDepth;
if(peek.left!=null) queue.offer(peek.left);
if(peek.right!=null) queue.offer(peek.right);
}
}
return minDepth;
}

104. 二叉树的最大深度
104. 二叉树的最大深度
就是返回层数。
public int maxDepth(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
if (root==null) return 0;
int depth = 0;
while (!queue.isEmpty()){
depth++;
int len = queue.size()-1;
while (len-->=0){
TreeNode peek = queue.poll();
if(peek.left!=null) queue.offer(peek.left);
if(peek.right!=null) queue.offer(peek.right);
}
}
return depth;
}

貌似用递归效率更高
public int maxDepth(TreeNode root) {
if(root!=null){
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
if(leftDepth>rightDepth) return leftDepth+1;
else return rightDepth+1;
}
return 0;
}

226. 翻转二叉树
下面这两道题是一样的
226. 翻转二叉树
剑指 Offer 27. 二叉树的镜像
遍历每一个节点,交换左右子树。
public TreeNode invertTree(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
if (root==null) return null;
while (!queue.isEmpty()){
int len = queue.size()-1;
while (len-->=0){
TreeNode peek = queue.poll();
if (peek!=null)swap(peek);
if(peek.left!=null) queue.offer(peek.left);
if(peek.right!=null) queue.offer(peek.right);
}
}
return root;
}
public static void swap(TreeNode root) {
TreeNode temp =root.left;
root.left = root.right;
root.right = temp;
}


总结
很多简单的问题都能通过层次遍历解决,较难的就要通过递归了.
边栏推荐
猜你喜欢
随机推荐
2.ROS通信机制
2017-06-11 Padavan 完美适配newifi mini【adbyby+SS+KP ...】youku L1 /小米mini
Redis常用命令
pta a.1003 的收获
【frp内网穿透】
-角谷猜想-
pta a.1030的dijkstra+DFS方法
一维数组和二维数组的命名以及存储空间
-最低分-
7.18(7)
【Flask】Flask-SQLAlchemy的增删改查(CRUD)操作
-寻找鞍点-
flask 面试题 问题
【数组】arr,&arr,arr+1,&arr+1以及内存单元的占用
web安全-命令执行漏洞
经典论文-ResNet
【编程学习新起点】记录写博客的第一天
【数组排序】+日常
C语言简单实现三子棋小游戏
Delightful Nuxt3 Tutorial (1): Application Creation and Configuration




![二叉树的合并[C]](/img/c2/08535044681dd477c0028b4306b77e.png)




