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

(leetcode)Symmetric Tree

时间:2015-07-31 21:40:31      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

判断一颗二叉树是否为对称的,思路如下:

  1)判断递归左右子树是否相等,通过比较左子树的左孩子和有右子树的右孩子,左子树的右孩子和右子树的左孩子。

class Solution {
public:
    bool isJudge(TreeNode* left, TreeNode* right){
        
        if(!left && !right) return true;
        if((!left && right) ||(left && !right) || (left->val != right->val)) return false;
        return isJudge(left->left,right->right) && isJudge(left->right,right->left);
    }
    bool isSymmetric(TreeNode* root) {
        if(root==NULL || (!root->left && !root->right)) return true;
        return isJudge(root->left,root->right);
     
    }
};

2)非递归算法(未能AC)

class Solution {
public:
    void inorder(TreeNode* root, vector<int>& res){
        if(!root) return;
        if((!root->left && root->right) || (root->left && !root->right)) return;
        inorder(root->left,res);
        res.push_back(root->val);
        inorder(root->right,res);
    }
    bool isSymmetric(TreeNode* root) {
        if(!root) return true;
        vector<int> res;
        inorder(root,res);
        int len = res.size();

      for(int i=0,j=len-1; i < j;++i,--j){
        if(res[i] != res[j]){

return false;
            }
        }
        return true;
    }
};

3)使用层次便利方法,用迭代方法进行判断(依然为AC)。

技术分享
class Solution {
public:
    bool isSymmetric(TreeNode* root) {
       if(!root || (!root->left && !root->right)) return true;
       queue<TreeNode*> lt,rt;//分别将根节点左子树和右子树的节点进入队列。
       if((!root->left && root->right) || (root->left && !root->right)) return false;
       lt.push(root->left);
       rt.push(root->right);
       TreeNode* l;
       TreeNode* r;
       while(!lt.empty() && !rt.empty())
       {
           l = lt.front();lt.pop();
           r = rt.front();rt.pop();
           if(l->val != r->val)
           {
               return false;
           }
           lt.push(l->left);
           lt.push(l->right);
           rt.push(r->right);
           rt.push(r->left);
       }
       return true;
    }
};
View Code

 

(leetcode)Symmetric Tree

标签:

原文地址:http://www.cnblogs.com/chdxiaoming/p/4693170.html

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