zoukankan      html  css  js  c++  java
  • LeetCode 101. Symmetric Tree 判断对称树 C++

    Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

    For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

        1
       / 
      2   2
     /  / 
    3  4 4  3

    But the following [1,2,2,null,3,null,3] is not:

        1
       / 
      2   2
          
       3    3

    Note:
    Bonus points if you could solve it both recursively and iteratively.

    判断是否是对称树和判断两棵树是否相同是一样的思路。

    第一种方法:使用递归(C++)

     1     bool leftEqualRight(TreeNode* left,TreeNode* right){
     2         if(!left&&!right)
     3             return true;
     4         if((!left&&right)||(left&&!right)||(left->val!=right->val))
     5             return false;
     6         return leftEqualRight(left->left,right->right)&&leftEqualRight(left->right,right->left);
     7     }
     8     
     9     bool isSymmetric(TreeNode* root) {
    10         if(!root)
    11             return true;
    12         return leftEqualRight(root->left,root->right);
    13     }

    第二种方法:使用迭代(C++),利用两个队列来分别存储根节点的左、右子树。首先,根节点为空,则对称,将根节点的左右子树分别压入两个队列,循环判断的条件是两个队列都不为空,当两个出队的结点都为空时,continue跳过此次判断,继续进行,当其中一个节点为空时,或者两个结点的值不相等时,跳出,false,再分别将两个结点的子树压入,左子树的左结点对应右子树的右结点,左子树的右结点对应右子树的左结点。

     1 bool isSymmetric(TreeNode* root) {
     2         if(!root)
     3             return true;
     4         queue<TreeNode*> q1,q2;
     5         q1.push(root->left);
     6         q2.push(root->right);
     7         while(!q1.empty()&&!q2.empty()){
     8             TreeNode* node1=q1.front();
     9             q1.pop();
    10             TreeNode* node2=q2.front();
    11             q2.pop();
    12             if(!node1&&!node2)
    13                 continue;
    14             if((!node1&&node2)||(node1&&!node2)||(node1->val!=node2->val))
    15                 return false;
    16             q1.push(node1->left);
    17             q2.push(node2->right);
    18             q1.push(node1->right);
    19             q2.push(node2->left);
    20         }
    21         return true;
    22     }
  • 相关阅读:
    mmall商城用户模块开发总结
    Hadoop伪分布式安装与配置
    1.2假设空间
    1.1基本术语
    文献笔记
    文献下载
    文献管理
    文献检索
    python:函数详解2
    python:函数详解
  • 原文地址:https://www.cnblogs.com/hhhhan1025/p/10686499.html
Copyright © 2011-2022 走看看