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 is symmetric:

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

But the following is not:

    1
   / \
  2   2
   \   \
   3    3

递归

bool isSymmetric(TreeNode* root) {
    if(root == NULL) return true;
    return compare2Tree(root->left, root->right);
}

//对称的部分比较
bool compare2Tree(TreeNode* root1, TreeNode* root2){
    if(root1 == NULL && root2 == NULL) return true;
    if(root1 == NULL || root2 == NULL) return false;
    
    if(root1->val == root2->val)
        return compare2Tree(root1->right, root2->left) && compare2Tree(root1->left, root2->right);
    else
        return false;
}

迭代

bool isSymmetric(TreeNode* root) {
    if(root == NULL) return true;
    //用栈模拟深度优先
    stack<TreeNode*> s;
    s.push(root->right);
    s.push(root->left);
    
    TreeNode* root1, * root2;
    while(!s.empty()){        
        root1 = s.top();
        s.pop();
        root2 = s.top();
        s.pop();
        
        if(root1 == NULL && root2== NULL) continue;
        if(root1 == NULL || root2== NULL) return false;
        if(root1->val != root2->val) return false;        
        
        s.push(root2->left);
        s.push(root1->right);
        s.push(root2->right);
        s.push(root1->left);
    }
    return true;
}

你可能感兴趣的:(101. Symmetric Tree)