您的位置:首页 > 其它

LeetCode(100)题解--Same Tree

2015-10-08 22:23 423 查看
https://leetcode.com/problems/same-tree/

题目:

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.

思路: DFS

AC代码:

1.递归

/**
* 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) {
if (p==NULL && q==NULL)
return true;
else if(p!=NULL&&q!=NULL){
bool ju;
if(p->val==q->val)
ju=true;
else
return false;
if (p->left==NULL && q->left==NULL)
;
else if(p->left!=NULL && q->left!=NULL)
ju=ju&&isSameTree(p->left,q->left);
else
return false;
if (p->right==NULL && q->right==NULL)
;
else if(p->right!=NULL && q->right!=NULL)
ju=ju&&isSameTree(p->right,q->right);
else
return false;
return ju;
}
else
return false;
}
};


2.非递归

/**
* 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) {
if(p==NULL&&q==NULL)
return true;
else if(p!=NULL && q!=NULL){
stack<TreeNode*> ms1,ms2;
ms1.push(p);
ms2.push(q);
TreeNode* p1,*q1;
while(!ms1.empty()){
p1=ms1.top();
q1=ms2.top();
if(p1->val!=q1->val)
return false;
else{
ms1.pop();
ms2.pop();
if(p1->right==NULL&&q1->right==NULL)
;
else if(p1->right!=NULL&&q1->right!=NULL){
ms1.push(p1->right);
ms2.push(q1->right);
}
else
return false;
if(p1->left==NULL&&q1->left==NULL)
;
else if(p1->left!=NULL&&q1->left!=NULL){
ms1.push(p1->left);
ms2.push(q1->left);
}
else
return false;
}
}
return true;
}
else
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: