您的位置:首页 > 其它

Same Tree

2015-07-28 13:07 246 查看
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.

Analyse: Compare all nodes in the same place.

1. Recursion

Runtime: 0ms.

/**
* 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 && !q) return true;
if(!p || !q) return false; //the first line eliminated the situation s.t. both trees are null
return p->val == q->val &&
isSameTree(p->left, q->left) &&
isSameTree(p->right, q->right);
}
};


2. Iteration with stack used

Runtime: 0ms.

/**
* 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* > stk;
stk.push(p);
stk.push(q);

while(!stk.empty()){
p = stk.top();
stk.pop();
q = stk.top();
stk.pop();

if(!p && !q) continue;
if(!p || !q) return false;
if(p->val != q->val) return false;

stk.push(p->left);
stk.push(q->left);
stk.push(p->right);
stk.push(q->right);
}
return true;
}
};


3. Iteration with queue used

Runtime: 4ms.

/**
* 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) {
queue<TreeNode* > qu;
qu.push(p);
qu.push(q);

while(!qu.empty()){
p = qu.front();
qu.pop();
q = qu.front();
qu.pop();

if(!p && !q) continue;
if(!p || !q) return false;
if(p->val != q->val) return false;

qu.push(p->left);
qu.push(q->left);
qu.push(p->right);
qu.push(q->right);
}
return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: