一、#226.翻转二叉树
题目:https://leetcode.cn/problems/invert-binary-tree/
视频:https://www.bilibili.com/video/BV1sP4y1f7q7
讲解:https://programmercarl.com/0226.%E7%BF%BB%E8%BD%AC%E4%BA%8C%E5%8F%89%E6%A0%91.html
注意这里交换的是指针,不是结点。
递归思路:先翻转root的左子树,再翻转右子树,最后root的左右子树进行翻转
前序遍历,后序遍历都可以,但是中序不行,因为中序的话会把某些节点翻转两遍
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null) return null;
invertTree(root.left); //翻转左子树
invertTree(root.right); //翻转右子树
swapChildren(root); //最后root的左右子树进行翻转
return root;
}
private void swapChildren(TreeNode root){
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
}
}
二、101. 对称二叉树
题目:https://leetcode.cn/problems/symmetric-tree/
视频:https://www.bilibili.com/video/BV1ue4y1Y7Mf
讲解:https://programmercarl.com/0101.%E5%AF%B9%E7%A7%B0%E4%BA%8C%E5%8F%89%E6%A0%91.html
此题用后序遍历,体现在最后三行;
如果是其他两种遍历,就是换最后三行的顺序,换了没法比了
class Solution {
public boolean isSymmetric(TreeNode root) {
return compare(root.left, root.right);
}
private boolean compare(TreeNode left, TreeNode right){
//左空右不空,不是对称,false
if(left == null && right != null) return false;
//左不空右空,不是对称,false
if(left != null && right == null) return false;
//左空右空,对称,true
if(left == null && right == null) return true;
//左右都不空,但是值不等,false
if(left.val != right.val) return false;
//比较外侧和内侧结点的结果
boolean compareOutside = compare(left.left, right.right); //左
boolean compareInside = compare(left.right, right.left); //右
return compareOutside && compareInside; //中
}
}
【递归算法很难?小s带你10分钟完成手把手推导,用递归求二叉树深度】
三、104.二叉树的最大深度
题目:https://leetcode.cn/problems/maximum-depth-of-binary-tree/
视频:https://www.bilibili.com/video/BV1Gd4y1V75u
讲解:https://programmercarl.com/0104.%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E5%A4%A7%E6%B7%B1%E5%BA%A6.html

求高度:用后序遍历,如果用的是左右中,可以把中的结果返回给父节点,继续往上遍历;
求深度:用前序遍历,可以求完子树之后,继续往下遍历
根节点的高度,就是此棵二叉树的最大深度,所以此题求最大深度;
左子树的深度和右子树的深度,取两者之中的最大值,+1就是最大深度。
class Solution {
public int maxDepth(TreeNode root) {
return getHeight(root);
}
private int getHeight(TreeNode node){
if(node == null) return 0;
int leftHeight = getHeight(node.left);
int rightHeight = getHeight(node.right);
int hight = Math.max(leftHeight, rightHeight) + 1;
return hight;
}
}
四、111.二叉树的最小深度
题目:https://leetcode.cn/problems/minimum-depth-of-binary-tree/
视频:https://www.bilibili.com/video/BV1QD4y1B7e2
讲解:https://programmercarl.com/0111.%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E5%B0%8F%E6%B7%B1%E5%BA%A6.html#%E7%AE%97%E6%B3%95%E5%85%AC%E5%BC%80%E8%AF%BE
这道题本来以为是上道题最后结果改成取两者最小值就行,大错特错!
注意读题:题中说,最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
class Solution {
public int minDepth(TreeNode root) {
if(root == null) return 0;
if(root.left==null && root.right==null) return 1;
if(root.left == null){
return minDepth(root.right)+1; //1
}
if(root.right == null){
return minDepth(root.left)+1;
}
return Math.min(minDepth(root.right),minDepth(root.left))+1;
}
}
1、这里的return:在递归函数中,return语句用于将递归调用的结果逐层向上返回,直到最终结果被返回到最初的调用点。可以理解为栈,一层栈帧执行结束之后,把结果用return返回给下一层栈帧。
575

被折叠的 条评论
为什么被折叠?



