您的位置:首页 > 其它

LeetCode:Same Tree

2016-06-05 10:20 330 查看


Same Tree

Total Accepted: 132356 Total
Submissions: 304237 Difficulty: Easy

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.

Subscribe to see which companies asked this question

Hide Tags
 Tree Depth-first
Search

c++ code:

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
bool isSam;
/*
void preOrder(TreeNode* p, TreeNode* q)
{
if(!isSam) return;
if(NULL == p && NULL == q) return;
if(NULL == p && NULL!= q || NULL != p && NULL== q)
{
isSam = false;
return;
}
if(p->val != q->val)
{
isSam = false;
return;
}
preOrder(p->left, q->left);
preOrder(p->right, q->right);
}
*/
void inOrder(TreeNode* p, TreeNode* q)
{
if(!isSam) return;
if(NULL == p && NULL == q) return;
if(NULL == p && NULL!= q || NULL != p && NULL== q)
{
isSam = false;
return;
}
inOrder(p->left, q->left);
if(p->val != q->val)
{
isSam = false;
return;
}
inOrder(p->right, q->right);
}

class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
isSam = true;
//preOrder(p,q);
inOrder(p,q);
return isSam;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: