19.LeetCode之对称二叉树

给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
    1
   / \
  2   2
 / \ / \
3  4 4  3

但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
    1
   / \
  2   2
   \   \
   3    3

说明:可以运用递归和迭代两种方法解决这个问题

C代码:递归

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

typedef struct TreeNode  Node;
bool isSymmetric2(struct TreeNode* p, struct TreeNode* q );

//二叉树——>两个子树
bool isSymmetric(struct TreeNode* root) {
    if( root == NULL )
        return true;
    return isSymmetric2( root->left, root->right );
}

//对两个对称子树进行递归比较
bool isSymmetric2(struct TreeNode* p, struct TreeNode* q ){
    if( p==NULL && q==NULL )
        return true;
    
    if( p!=NULL && q!=NULL && p->val==q->val)
        return isSymmetric2(p->left, q->right) && isSymmetric2(p->right, q->left);
    else
        return false;
}

C++代码:用队列Queue进行迭代 (C语言实现队列比较麻烦,故使用C++)

/**
 * 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) 
            return true;
        queue<TreeNode*> q;
        q.push(root); //根节点二次入队,模拟对称过程
        q.push(root);
        while( !q.empty() )
        {
            TreeNode* t1 = q.front(); q.pop(); //pop()无返回值,作用是清除队首元素
            TreeNode* t2 = q.front(); q.pop(); //front()返回队首元素,但不清除元素
            if( t1==NULL && t2==NULL ) 
                continue;
            if( t1==NULL || t2==NULL ) 
                return false;
            if( t1->val != t2->val ) 
                return false;
            q.push(t1->left); //入队方式
            q.push(t2->right);
            q.push(t1->right);
            q.push(t2->left);
        }
        return true;
    }
};

C++代码:用栈Stack进行迭代 (C语言实现栈比较麻烦,故使用C++)

/**
 * 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)
            return true;
        stack<TreeNode*> s;
        s.push(root->left);
        s.push(root->right);
        TreeNode *t1,*t2;
        while(!s.empty()){
            t1=s.top(), s.pop(); //pop()无返回值,作用是清除栈顶元素
            t2=s.top(), s.pop(); //top()返回栈顶元素,但不清除元素
            if( !t1 && !t2 ) 
                continue;
            if( !t1 || !t2 )
                return false;
            if( t1->val != t2->val ) 
                return false;
            s.push(t1->left); //按照对称元素连续的次序入栈
            s.push(t2->right);
            s.push(t1->right);
            s.push(t2->left);
        }
        return true;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_39564672/article/details/88189277
今日推荐