leetcode 101. Symmetric Tree 判断二叉树是否左右对称

https://leetcode.com/problems/symmetric-tree/

leetcode 101. Symmetric Tree 判断二叉树是否左右对称_第1张图片

1.递归

/**
 * 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 verify(root->left, root->right);
    }
    bool verify(TreeNode* left, TreeNode* right){
        if(left==nullptr && right==nullptr) return true;
        if(left==nullptr || right==nullptr) return false;
        return left->val == right->val && verify(left->left, right->right) && verify(left->right, right->left);
    }
};

 

2.非递归

用栈来存储左右节点

/**
 * 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;
        stack s;
        s.push(root->left);
        s.push(root->right);
        
        while(!s.empty()){
            TreeNode* p = s.top();
            s.pop();
            TreeNode* q = s.top();
            s.pop();
            
            if(p==nullptr && q==nullptr) continue;
            if(p==nullptr || q==nullptr) return false;
            if(p->val != q->val) return false;
            s.push(p->left);
            s.push(q->right);
            
            s.push(p->right);
            s.push(q->left);
        }
        return true;
    }
};

其他思路:先将右子树做对称处理,再判断左右子树是否相等

/**
 * 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;
        if(root->left==nullptr && root->right==nullptr) return true;
        else if(root->left!=nullptr && root->right!=nullptr){
            root->right = symme(root->right);
            return verify(root->left, root->right);
        }
        return false;
    }
    
    TreeNode* symme(TreeNode* root){//将二叉树左右对调
        if(root==nullptr)return root;
        TreeNode* tmp = root->left;
        root->left = symme(root->right);
        root->right= symme(tmp);
        return root;
    }
    
    bool verify(TreeNode* r1, TreeNode* r2){//判断两个二叉树是否相同
        if(r1==nullptr && r2==nullptr) return true;
        else if(r1!=nullptr && r2!=nullptr){
            if(r1->val == r2->val){
                return verify(r1->left, r2->left) && verify(r1->right, r2->right);
            }
        }
        return false;
    }
};

 

你可能感兴趣的:(leetcode)