LeetCode:Same Tree
2016-06-05 10:20
330 查看
Same Tree
Total Accepted: 132356 TotalSubmissions: 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;
}
};
相关文章推荐
- 算法分析中递推式的一般代数解法
- CTF 【每日一题20160605】
- LaTeX快速入门-蔡炎龙
- 使用WebService的优点
- Smarty基础
- 集成友盟分享总结
- [置顶] 《App后台开发运维和架构实践》前言
- 敏捷(AGILE)开发及其幕后的设计思维
- JAVA_OA(bug篇)(一):SpringMVC的bug1
- Spring学习(十七)Spring 参数注入方式介绍
- Grails里DOMAIN类的一对一,一对多,多对多关系总结及集成测试
- Facebook发布人工智能产品DeepText:能以人类智商
- 多项式曲线拟合(Polynomial Curve Fitting)
- LeetCode:Reverse String
- java实现登陆界面
- Kth Smallest Element in a BST
- 基于FO图形库实现电网动态拓扑着色研究与分析
- Sublime注册码
- java多线程ReentrantLock、sync、ReentrantReadWriteLock性能比较
- Hive框架