Leet Code 100 Same Tree
2015-11-22 16:47
519 查看
Same Tree
QuestionTotal Accepted: 94258 Total
Submissions: 224120 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
Show Tags
11
如果两棵树都为空,那么应该是相同的.
如果两棵树一棵为空,一棵树非空,那么是不同的
如果两棵树都不为空,但是根节点的值不同,那么两棵树不同
如果两个树根节点数据相同,就递归判断它们的左子树和又子树是否都相同.
/** * 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||!q&&p||p->val!=q->val) return false; return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right); } };
相关文章推荐
- EMC的一道数字编程编程题
- 什么是http头信息
- Xcode cannot run using the selected device-无法真机调试
- js数组存储对象及对象的获取
- easyui环境搭建02
- HDU 2070 叠框
- 多媒体封装格式学习:H264封装成FLV(二)
- tcpdump 参数详解
- 更改Apache默认网站根目录
- Unique Paths II-leetcode
- Android 实现滑动的几种方法(一)onLayout方法 和 offsetLeftAndRight()与offsetTopAndBottom();
- 小技巧之nvidia-smi
- res里面的drawable(ldpi、mdpi、hdpi、xhdpi、xxhdpi)
- JSP中getParameter与getAttribute有何区别?
- cocoapods 0.35.0 版本 报错 Parsing unable to continue due to parsing error:
- HDU1032&Uva100 The 3n + 1 problem
- qt 窗口置顶/真透明/背景模糊/非矩形/跳过任务栏分页器/无边框/无焦点点击/焦点穿透
- java--I/O流总结
- jsp 内置对象
- c++ vector(向量)使用方法详解(顺序访问vector的多种方式)