剑指 Offer 27. 二叉树的镜像
- 二叉树的镜像翻转使用深度优先搜索=递归的方法,使左节点=右节点
- 递归的终止条件是:节点为空。
- 或者使用广度优先搜索,使用辅助栈交换左右节点。
递归思路:
递归解析:
终止条件: 当节点 rootroot 为空时(即越过叶节点),则返回 nullnull ;
递推工作:
初始化节点 tmptmp ,用于暂存 rootroot 的左子节点;
开启递归 右子节点 mirrorTree(root.right)mirrorTree(root.right) ,并将返回值作为 rootroot 的 左子节点 。
开启递归 左子节点 mirrorTree(tmp)mirrorTree(tmp) ,并将返回值作为 rootroot 的 右子节点 。
返回值: 返回当前节点 rootroot ;
作者:jyd
链接:https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof/solution/mian-shi-ti-27-er-cha-shu-de-jing-xiang-di-gui-fu-/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution {
public TreeNode mirrorTree(TreeNode root) {
if (root == null) {
return null;
}
TreeNode left = mirrorTree(root.left);
TreeNode right = mirrorTree(root.right);
root.left = right;
root.right = left;
return root;
}
}
剑指 Offer 28. 对称的二叉树
- 递归的比较左右节点的值是否一致
- 递归的终止条件是,左右子节点度为空;左右子节点不相等
class Solution {
public boolean isSymmetric(TreeNode root) {
return root == null ? true : recur(root.left, root.right);
}
boolean recur(TreeNode L, TreeNode R) {
if(L == null && R == null) return true;
if(L == null || R == null || L.val != R.val) return false;
return recur(L.left, R.right) && recur(L.right, R.left);
}
}