今天开始刷二叉树的题目,发现大多数都是在昨天的遍历的基础上的变式
226.翻转二叉树
根据题目描述模拟整个交换过程,发现非常像前序遍历的递归方式:每次先将当前节点的左右孩子互换,再递归左右孩子,当节点为空的时候停下。(实际上看了题解发现除了中序遍历先处理了左边,回到中间节点时将左右颠倒了,之后处理“右边”部分相当于把左边转了回来。可以把处理完中间节点的代码改成依然处理左边)
我最开始在写题的时候将交换功能单独写了个函数swap,但测试发现根本没更改节点,查资料发现Java函数只有值传递,所以交换的都是传入参数的副本。因此交换的代码需要写在递归函数里面。
class Solution {
public TreeNode invertTree(TreeNode root) {
invert(root);
return root;
}
void invert(TreeNode node) {
if (node == null) return;
TreeNode tmp = node.left;
node.left = node.right;
node.right = tmp;
invert(node.left);
invert(node.right);
}
}
101. 对称二叉树
发现本质是判断两个子树的内侧节点和外侧节点值是否相等,这种递归就需要两个参数,套路是从第二层开始找规律。这题的递归结束条件是对称两侧都为空,boolean返回值需要处理两个结束条件
class Solution {
public boolean isSymmetric(TreeNode root) {
return is(root.left,root.right);
}
public boolean is(TreeNode left,TreeNode right){
if(left==null && right==null) return true;
if(left==null || right==null) return false;
return left.val==right.val && is(left.left,right.right) && is(left.right,right.left);
}
}
104.二叉树的最大深度
比较简单,递归条件为节点为空,每次进入递归+1
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
}
}
111.二叉树的最小深度
本来以为跟上面一题一样,测试用例一看发现如果出现节点一边没有孩子的情况会误判
因此需要额外判断左右边是否直接空了,空了就返回另一侧+1
class Solution {
public int minDepth(TreeNode root) {
if (root == null) return 0;
if (root.left == null) return minDepth(root.right)+1;
if (root.right == null) return minDepth(root.left)+1;
return Math.min(minDepth(root.left),minDepth(root.right))+1;
}
}