码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 101 Symmetric Tree (C)

时间:2016-10-17 00:04:35      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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)

标签:

原文地址:http://www.cnblogs.com/calvin2/p/5968106.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!