首页 > 代码库 > LeetCode 101 Symmetric Tree (C)

LeetCode 101 Symmetric Tree (C)

题目:

101. Symmetric Tree

 
 My Submissions
 
  • Total Accepted: 135232
  • Total Submissions: 375037
  • Difficulty: Easy
  • Contributors: Admin

 

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

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   /   2   2
 / \ / 3  4 4  3

 

But the following [1,2,2,null,3,null,3] is not:

    1
   /   2   2
   \      3    3

 

Note:
Bonus points if you could solve it both recursively and iteratively.

 

提示:

Tree  Depth-first Search  Breadth-first Search

 

方法1:(效率低,自己写的)

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

bool compare(struct TreeNode* lnode, struct TreeNode* rnode){
    if(lnode->val==rnode->val){
        if(lnode->left!=NULL && rnode->right!=NULL && lnode->right!=NULL && rnode->left!=NULL){
            return compare(lnode->left, rnode->right) && compare(lnode->right, rnode->left);
        }
        else if(lnode->left!=NULL && rnode->right!=NULL && lnode->right==NULL && rnode->left==NULL){
            return compare(lnode->left, rnode->right);
        }
        else if(lnode->left==NULL && rnode->right==NULL && lnode->right!=NULL && rnode->left!=NULL){
            return compare(lnode->right, rnode->left);
        }
        else if(lnode->left==NULL && rnode->right==NULL && lnode->right==NULL && rnode->left==NULL){
            return true;
        }
        else
            return false;
    }
    else 
        return false;
}


bool isSymmetric(struct TreeNode* root) {
    if(root==NULL){
        return true;
    }
    else if(root->left==NULL && root->right==NULL){
        return true;
    }
    else if(root->left!=NULL && root->right!=NULL){
        return compare(root->left, root->right);
    }
    else
        return false;
}

 

LeetCode 101 Symmetric Tree (C)