找回密码
 立即注册
首页 业界区 科技 给定二叉树的根节点 root,判断它是否 轴对称(镜像对称 ...

给定二叉树的根节点 root,判断它是否 轴对称(镜像对称)

屠焘 昨天 18:31
题目:给你一个二叉树的根节点 root , 检查它是否轴对称。
1.png


这个题的思路是,把「轴对称」转化为「两棵子树互为镜像」的问题:

  • 递归比较:左子树的左孩子 vs 右子树的右孩子,左子树的右孩子 vs 右子树的左孩子。
  • 迭代法:可用队列/栈每次成对弹出节点比较。
复杂度:
时间复杂度:O(n),每个节点访问一次
空间复杂度:

  • 递归:O(h)(栈深度)
  • 迭代:O(n)(队列最大宽度)
1、递归比较
  1. class Solution {
  2.     public boolean isSymmetric(TreeNode root) {
  3.         if(root==null){
  4.             return true;
  5.         }
  6.         if(root.left==null && root.right==null){
  7.             return true;
  8.         }
  9.         if(root.left==null || root.right==null){
  10.             return false;
  11.         }
  12.    
  13.         // 判断左右子树是否镜像对称
  14.         return isMirror(root.left, root.right);
  15.         
  16.     }
  17.     private boolean isMirror(TreeNode t1, TreeNode t2){
  18.         if(t1==null && t2==null){
  19.             return true;
  20.         }
  21.         if(t1==null || t2==null){
  22.             return false;
  23.         }
  24.         // 递归比较:
  25.         // 1.左子树 vs 右子树
  26.         // 2.左子树的左孩子 vs 右子树的右孩子
  27.         // 3.左子树的右孩子 vs 右子树的左孩子
  28.         if(t1.val == t2.val && isMirror(t1.left, t2.right) && isMirror(t1.right, t2.left)){
  29.             return true;
  30.         }else{
  31.             return false;
  32.         }
  33.     }
  34. }
复制代码
2、迭代法(队列双指针)
  1. class Solution {
  2.     public boolean isSymmetric(TreeNode root) {
  3.         if (root == null) return true;
  4.         Queue<TreeNode> q = new LinkedList<>();
  5.         q.offer(root.left);
  6.         q.offer(root.right);
  7.         while (!q.isEmpty()) {
  8.             TreeNode t1 = q.poll();
  9.             TreeNode t2 = q.poll();
  10.             if (t1 == null && t2 == null) continue;
  11.             if (t1 == null || t2 == null || t1.val != t2.val) return false;
  12.             q.offer(t1.left);  q.offer(t2.right);
  13.             q.offer(t1.right); q.offer(t2.left);
  14.         }
  15.         return true;
  16.     }
  17. }
复制代码
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册