zoukankan      html  css  js  c++  java
  • [LeetCode] 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.

    判断一棵树的对称性,利用递归按照对称树的性质判断即可。

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        bool isSymmetric(TreeNode* root) {
            if (root == nullptr)
                return true;
            return isSymmetricCore(root->left, root->right);
        }
        bool isSymmetricCore(TreeNode* s, TreeNode* t) {
            if (s == nullptr && t == nullptr)
                return true;
            if (s == nullptr || t == nullptr)
                return false;
            if (s->val != t->val)
                return false;
            return isSymmetricCore(s->left, t->right) && isSymmetricCore(s->right, t->left);
        }
    };
    // 3 ms

     用迭代来表述算法,利用两个queue维护一棵树根节点的左右两棵子树节点。然后判断相对应的节点

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        bool isSymmetric(TreeNode* root) {
            if (root == nullptr)
                return true;
            queue<TreeNode*> q1, q2;
            q1.push(root->left);
            q2.push(root->right);
            while (!q1.empty() && !q2.empty()) {
                TreeNode* node1 = q1.front();
                TreeNode* node2 = q2.front();
                q1.pop();
                q2.pop();
                if ((node1 == nullptr && node2 != nullptr) || (node1 != nullptr && node2 == nullptr))
                    return false;
                if (node1 != nullptr && node2 != nullptr) {
                    if (node1->val != node2->val)
                        return false;
                    q1.push(node1->left);
                    q1.push(node1->right);
                    q2.push(node2->right);
                    q2.push(node2->left);
                }
            }
            return true;
        }
    };
    // 3 ms
  • 相关阅读:
    小刘同学的第一百五十二篇日记
    小刘同学的第一百五十一篇日记
    小刘同学的第一百五十篇日记
    小刘同学的第一百五十篇日记
    小刘同学的第一百四十九篇日记
    小刘同学的第一百四十八篇日记
    小刘同学的第一百四十七篇日记
    小刘同学的第一百四十六篇日记
    小刘同学的第一百四十五篇博文
    自定义CollectionViewLayout
  • 原文地址:https://www.cnblogs.com/immjc/p/7435876.html
Copyright © 2011-2022 走看看