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

leetcode No100. Same Tree

时间:2016-08-19 10:03:19      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:

Question:

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

判断两颗二叉树是否相同

Algorithm:

1、递归
2、BFS宽度优先搜索(DFS也可以)

Accepted Code:

算法1、(17.62%)
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        bool leftsame = 0;
        bool rightsame = 0;
        if((p==NULL)&&(q==NULL))return true;
        else if((p==NULL)&&(q!=NULL))return false;
        else if((p!=NULL)&&(q==NULL))return false;
        if(p->val != q->val)return false;
        leftsame = isSameTree(p->left,q->left);
        rightsame = isSameTree(p->right,q->right);
       
        return (leftsame&&rightsame);
    }
};

算法2、(7.64%)
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        stack<TreeNode*> s1;
        stack<TreeNode*> s2;
        if(p==NULL&&q==NULL)
            return true;
        else if(p!=NULL&&q!=NULL)
        {
           s1.push(p);
            s2.push(q); 
        }
        else
            return false;
        while(!s1.empty()&&!s2.empty())
        {
            TreeNode* t1=s1.top();
            TreeNode* t2=s2.top();
            if(t1->val!=t2->val)
                return false;
            s1.pop();
            s2.pop();
            if(t1->left&&t2->left)
            {
                s1.push(t1->left);
                s2.push(t2->left);
            }
            else if((t1->left==NULL^t2->left==NULL)==1)
                return false;
            if(t1->right&&t2->right)
            {
                s1.push(t1->right);
                s2.push(t2->right);
            }
            else if((t1->right==NULL^t2->right==NULL)==1)
                return false;
        }
        if(s1.empty()&&s2.empty())
            return true;
        return false;
    }
};


leetcode No100. Same Tree

标签:

原文地址:http://blog.csdn.net/u011391629/article/details/52247565

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