在二叉树采取递归方式接替之前,除了要确认递归三部曲之外,还要注意根据题意选择二叉树的遍历方式,也就是处理逻辑放在左右子树遍历的前-中-后(先序-中序-后序)
对称
- 题目链接:反转二叉树
- 递归解法:采用先序遍历,只需要交换左右子树
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null) return root;
//先序翻转
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
//递归处理左右子树
root.left = invertTree(root.left);
root.right = invertTree(root.right);
return root;
}
}
-
复杂度:时间复杂度 O ( N ) O(N) O(N), 空间复杂度 O ( l o g 2 N ) O(log_{2}N) O(log2N)
-
题目链接:对称二叉树
-
递归解法:
class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null) return true;
return compare(root.left, root.right);
}
public boolean compare(TreeNode left, TreeNode right){
if(left == null && right == null) return true;
if(left == null && right != null) return false;
if(left != null && right == null) return false;
if(left.val != right.val) return false;
//镜面对称根节点需要的到下面两子树的返回值,使用后续
boolean l = compare(left.left, right.right);
boolean r = compare(left.right, right.left);
if(l && r) return true;
return false;
}
}
总结:当根节点需要左右子树的返回值时,考虑遍历处理逻辑为后序遍历。