101. Symmetric Tree

欢迎fork and star:Nowcoder-Repository-github

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. 

解析

  • 递归和迭代实现
// 101. Symmetric Tree
class Solution_101 {
public:

    // 递归调用,同时判断左子树的左节点与右子树的右节点,以及左子树的右节点与右子树的左节点。一旦这两个节点不相等,就返回false。 
    bool isSymmetricHelp(TreeNode *left, TreeNode* right)
    {
        if (!left&&!right)
        {
            return true;
        }
        if (!left&&right ||left&&!right)
        {
            return false;
        }
        if (left->val!=right->val)
        {
            return false;
        }

        return isSymmetricHelp(left->left, right->right) && isSymmetricHelp(left->right, right->left);
    }

    bool isSymmetric(TreeNode *root) {

        if (!root)
        {
            return true;
        }
        return isSymmetricHelp(root->left, root->right);
    }

    //非递归实现
    //需要:对每一层成对送入队列,出队列比较
    bool isSymmetric1(TreeNode* root) {
        if (!root)
        {
            return true;
        }
        queue<TreeNode*> que;

        que.push(root->left);
        que.push(root->right);

        while (!que.empty())
        {
            int size = que.size();
            while (size)
            {
                TreeNode* left = que.front();
                que.pop();
                TreeNode* right = que.front(); //取出成对的元素
                que.pop();
                size -= 2;
                if (!left&&!right)
                {
                    continue;
                }
                if (!left&&right)
                {
                    return false;
                }
                if (left&&!right)
                {
                    return false;
                }

                if (left->val!=right->val)
                {
                    return false;
                }
                que.push(left->left);
                que.push(right->right);
                que.push(left->right);
                que.push(right->left);
            }
        }
        return true;
    }
};

101. Symmetric Tree

    原文作者:ranjiewen
    原文地址: https://www.cnblogs.com/ranjiewen/p/8274528.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞