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

  • 相关阅读:
    hdu 4521 小明系列问题——小明序列(线段树 or DP)
    hdu 1115 Lifting the Stone
    hdu 5476 Explore Track of Point(2015上海网络赛)
    Codeforces 527C Glass Carving
    hdu 4414 Finding crosses
    LA 5135 Mining Your Own Business
    uva 11324 The Largest Clique
    hdu 4288 Coder
    PowerShell随笔3 ---别名
    PowerShell随笔2---初始命令
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6637566.html
Copyright © 2011-2022 走看看