先总结这三题好像都不算难☹️,但是都没做出来不是这里错就是那里错,归根结底还是对于递归不够理解。做了这么多遍的题目,下次遇到还是不会,这道题如何才能解决呢。每次看递归都是似懂非懂的太难受了。
104. 最大深度,不是前序就是后序了,但是我们之前的遍历都是遍历整颗树,然后获取节点就行了。这里的话,需要还是一样的遍历,只不过需要对两边的路径进行记录,然后比大小。你让我遍历我可以理解,但是每次递归的返回值就搞的乱七八糟的,还得多看看。这里又个图解还是蛮好的104. 二叉树的最大深度(后序或层序遍历,清晰图解)https://leetcode.cn/problems/maximum-depth-of-binary-tree/solutions/2361697/104-er-cha-shu-de-zui-da-shen-du-hou-xu-txzrx/
class Solution {
public int maxDepth(TreeNode root) {
if(root == null) return 0;
int leftDepth = maxDepth(root.left)+1;
int rightDepth = maxDepth(root.right)+1;
return Math.max(leftDepth, rightDepth);
}
}
111. 最小深度这里有个坑跟上一个题目不一样了,这里是求叶子结点到根的最短路径,而不是单单的一个最短深度了!好难🤯,下面是大佬的代码直接拿过来了。
class Solution {
public int minDepth(TreeNode root) {
if(root == null) return 0;
//这道题递归条件里分为三种情况
//1.左孩子和有孩子都为空的情况,说明到达了叶子节点,直接返回1即可
if(root.left == null && root.right == null) return 1;
//2.如果左孩子和由孩子其中一个为空,那么需要返回比较大的那个孩子的深度
int m1 = minDepth(root.left);
int m2 = minDepth(root.right);
//这里其中一个节点为空,说明m1和m2有一个必然为0,所以可以返回m1 + m2 + 1;
if(root.left == null || root.right == null) return m1 + m2 + 1;
//3.最后一种情况,也就是左右孩子都不为空,返回最小深度+1即可
return Math.min(m1,m2) + 1;
}
}
222. 这题呢,算是简单如果用普通遍历的话。但是可以结合完全二叉树的特性有更好的写法,我没看感觉先把递归理解好吧!
class Solution {
int count;
public int countNodes(TreeNode root) {
dfs(root);
return count
}
public void dfs(TreeNode root){
if(root==null) return;
count+=1;
dfs(root.left);
dfs(root.right);
}
}