对称的二叉树

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/N1neDing/article/details/85149364

题目描述

请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

代码1:

使用递归每次检查左子树的左(右)节点和右子树的右(左)节点

class Solution {
    bool res = true;
public:
    bool isSymmetrical(TreeNode* pRoot)
    {
        if (pRoot == NULL) return true;
        isSymmetricalHelper(pRoot->left, pRoot->right);
        return res;
         
    }
    void isSymmetricalHelper(TreeNode* node_left, TreeNode* node_right)
    {
        if (node_left == NULL && node_right == NULL) return;
        if ((node_left == NULL && node_right != NULL) || (node_left != NULL && node_right == NULL))
        {
            res = false;
            return;
        }
        if (node_left->val != node_right->val)
        {
            res = false;
            return;
        }
        isSymmetricalHelper(node_left->left, node_right->right);
        isSymmetricalHelper(node_left->right, node_right->left);
    }
};

代码2:

不使用递归,使用迭代,用一个queue每次比较头部元素是否满足。

class Solution {
public:
    bool isSymmetrical(TreeNode* pRoot)
    {
        if(pRoot == NULL)
        {
            return true;
        }
        queue<TreeNode*> leftTree;
        queue<TreeNode*> rightTree;
        leftTree.push(pRoot);
        rightTree.push(pRoot);
        while(leftTree.size() && rightTree.size())
        {
            TreeNode* tmpLeftNode = leftTree.front();
            TreeNode* tmpRightNode = rightTree.front();
            if(tmpLeftNode->val != tmpRightNode->val)
            {
                return false;
            }
            else
            {
                leftTree.pop();
                rightTree.pop();
                //judge left->left and right->right
                if(tmpLeftNode->left != NULL && tmpRightNode->right != NULL)
                {
                    leftTree.push(tmpLeftNode->left);
                    rightTree.push(tmpRightNode->right);
                }
                else if(tmpLeftNode->left != NULL && tmpRightNode->right == NULL)
                {
                    return false;
                }
                else if(tmpLeftNode->left == NULL && tmpRightNode->right != NULL)
                {
                    return false;
                }
                //judge left->right and right->left
                if(tmpLeftNode->right != NULL && tmpRightNode->left != NULL)
                {
                    leftTree.push(tmpLeftNode->right);
                    rightTree.push(tmpRightNode->left);
                }
                else if(tmpLeftNode->right != NULL && tmpRightNode->left == NULL)
                {
                    return false;
                }
                else if(tmpLeftNode->right == NULL && tmpRightNode->left != NULL)
                {
                    return false;
                }
            }
        }
        if(leftTree.empty() && rightTree.empty())
        {
            return true;
        }
        return false;
    }
};

 

展开阅读全文

没有更多推荐了,返回首页