leetcode_num101_Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following is not:

    1
   / \
  2   2
   \   \
   3    3

递归 依次比较左左、右右,左右、右左

/**
 * Definition for binary tree
 * 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;
        bool res=Compare(root->left,root->right);
        return res;
    }
    bool Compare(TreeNode*Left,TreeNode*Right){
        bool res=false;
        if(!Left&&!Right)
            return true;
        else if(Left&&Right&&Left->val==Right->val){
            bool check1=Compare(Left->left,Right->right);
            bool check2=Compare(Left->right,Right->left);
            res=check1&&check2;
        }
        return res;
    }
};



循环 使用两个栈分别按递归的顺序依次存储左子树和右子树的节点

尽量多写几种情况吧 不明白为何会报runtime error

 
  
class Solution {
public:
    bool isSymmetric(TreeNode *root) {
        if(!root||(!root->left&&!root->right))
            return true;
        stack stack1;
        stack stack2;
        stack1.push(root->left);
        stack2.push(root->right);

        while((!stack1.empty())&&(!stack2.empty())){
            TreeNode* L=stack1.top();
            TreeNode* R=stack2.top();
            stack1.pop();
            stack2.pop();
            if((!L)&&(!R))
                continue;
            if(!L||!R)
                return false;
            if(L->val!=R->val)
                return false;
            stack1.push(L->left);
            stack2.push(R->right);
            stack1.push(L->right);
            stack2.push(R->left);
        }
        return true;
        
    }
};


你可能感兴趣的:(c++,oj-leetcode)