ayaov

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

剑指 Offer 27. 二叉树的镜像

  1. 二叉树的镜像翻转使用深度优先搜索=递归的方法,使左节点=右节点
  2. 递归的终止条件是:节点为空。
  3. 或者使用广度优先搜索,使用辅助栈交换左右节点。
    递归思路:
  递归解析:
  终止条件: 当节点 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. 对称的二叉树

  1. 递归的比较左右节点的值是否一致
  2. 递归的终止条件是,左右子节点度为空;左右子节点不相等
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);
    }
}
posted on 2021-12-07 23:44  ayaov  阅读(22)  评论(0)    收藏  举报