剑指offer_二叉树---对称的二叉树

简介: 剑指offer_二叉树---对称的二叉树

##题目描述

请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

##解题思路

两种思路

1:构造自己的一颗镜像树,然后比对两颗树是否相同,相同则对称

2:直接让该树左子树的左子树和右子树的右子树交换,左子树的右子树和右子树的左子树交换,如果相同则对称

注意:根节点为null也算对称

##代码

/**
 * 
 */
package 二叉树;
/**
 * 请实现一个函数,用来判断一颗二叉树是不是对称的。 注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
 * 
 */
public class IsSymmetrical {
  // 如果相同,则是对称二叉树
  public boolean isSymmetrical(TreeNode pRoot) {
    TreeNode mirrorRoot = getMirror(pRoot);
    return TreeisEqual(pRoot, mirrorRoot);
  }
  // 比较两颗树是否相同
  public boolean TreeisEqual(TreeNode root1, TreeNode root2) {
    if (root1 == null && root2 == null) {
      return true;
    }  
    if (root1 == null || root2 == null) {
      return false;
    }
    if (root1.val != root2.val) {
      return false;
    }
    return TreeisEqual(root1.left, root2.left)
        && TreeisEqual(root1.right, root2.right);
  }
  // 获取该二叉树的镜像树
  public TreeNode getMirror(TreeNode pRoot) {
    if (pRoot == null) {
      return null;
    }
    TreeNode root = new TreeNode(pRoot.val);
    root.right = getMirror(pRoot.left);
    root.left = getMirror(pRoot.right);
    return root;
  }
  // =====================================================================优化算法
  public boolean isSymmetricalSuper(TreeNode pRoot) {
    if (pRoot == null) {
      return true;
    }
    return comRoot(pRoot.left, pRoot.right);
  }
  // 如果左子树的左子树和右子树的右子树相同,左子树的右子树和右子树的左子树相同即可
  public boolean comRoot(TreeNode left, TreeNode right) {
    // 如果左右子树都为空,递归结束
    if (left == null && right == null)
      return true;
    // 如果有一个为空,则说明不对称
    if (left == null || right == null)
      return false;
    // 如果都非空,则比较是否相等
    if (left.val != right.val)
      return false;
    return comRoot(left.right, right.left)
        && comRoot(left.left, right.right);
  }
  public static void main(String[] args) {
    // TODO Auto-generated method stub
  }
}


相关文章
|
1月前
|
Java C++ Python
leetcode-101:对称二叉树
leetcode-101:对称二叉树
31 0
|
7月前
Leetcode101.对称二叉树
Leetcode101.对称二叉树
19 0
|
8月前
【Leetcode -101.对称二叉树 -144.二叉树的前序遍历】
【Leetcode -101.对称二叉树 -144.二叉树的前序遍历】
20 0
|
8月前
代码随想录Day12 二叉树 LeetCode T102二叉树的层序遍历 T226 翻转二叉树 T101 对称二叉树
代码随想录Day12 二叉树 LeetCode T102二叉树的层序遍历 T226 翻转二叉树 T101 对称二叉树
49 0
|
1月前
LeetCode——101——对称二叉树
LeetCode——101——对称二叉树
48 12
|
1月前
【力扣刷题】二叉树的中序遍历、二叉树的最大深度、翻转二叉树、对称二叉树
【力扣刷题】二叉树的中序遍历、二叉树的最大深度、翻转二叉树、对称二叉树
22 0
LeetCode | 101. 对称二叉树
LeetCode | 101. 对称二叉树
|
1月前
二叉树OJ题:LeetCode--101.对称二叉树
二叉树OJ题:LeetCode--101.对称二叉树
26 0
|
1月前
leetcode:对称二叉树
leetcode:对称二叉树