zoukankan      html  css  js  c++  java
  • [leetcode-101-Symmetric Tree]

    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.

    思路:

    递归法:当要比较的两个结点有一个为空时返回false,当要比较的两个结点值不相等时返回false。 当两结点为空时即为true。

    非递归:层次遍历,需要注意的是左结点按照左右的顺序进入队列,而右边结点要按照先右后左顺序进入队列,这样比较的时候才满足是否对称要求。

    bool isSymmetric2(TreeNode *root)
        {//非递归 层次遍历二叉树
            TreeNode *left, *right;
            if (!root)
                return true;
            queue<TreeNode*> q1, q2;
            q1.push(root->left);
            q2.push(root->right);
            while (!q1.empty() && !q2.empty()){
                left = q1.front();
                q1.pop();
                right = q2.front();
                q2.pop();
                if (NULL == left && NULL == right)
                    continue;
                if (NULL == left || NULL == right)
                    return false;
                if (left->val != right->val)
                    return false;
                q1.push(left->left);
                q1.push(left->right);
                q2.push(right->right);
                q2.push(right->left);
            }
            return true;
        }
        bool isSymmetricCore(TreeNode* left, TreeNode* right)
        {
            if (left == NULL && right == NULL) return true;
            if (left == NULL && right != NULL || left != NULL && right == NULL || left->val != right->val)return false;
            return isSymmetricCore(left->left, right->right) && isSymmetricCore(left->right, right->left);//递归判断
        }
        bool isSymmetric(TreeNode* root)
        {
            if (root == NULL) return true;
            return isSymmetricCore(root->left, root->right);
        }

    参考:

    https://discuss.leetcode.com/topic/4332/my-c-accepted-code-in-16ms-with-iteration-solution

  • 相关阅读:
    IE6下不能定义1px高度的容器和IE6 双边距
    py django 渲染前端打包的视图
    关于常见的递推关系。
    题解:一些递推的题。
    题解:极值问题。
    题解:城南树林。
    题解:论编辑器的和谐共处。
    题解:左右横跳。
    题解:斑马,斑马(zebra)
    找 前端 私活
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6637566.html
Copyright © 2011-2022 走看看