LeetCode--Same Tree
来源:互联网 发布:淘宝能卖二手货吗 编辑:程序博客网 时间:2024/06/15 11:19
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
Example 1:
Input: 1 1 / \ / \ 2 3 2 3 [1,2,3], [1,2,3]Output: true
Example 2:
Input: 1 1 / \ 2 2 [1,2], [1,null,2]Output: false
Example 3:
Input: 1 1 / \ / \ 2 1 1 2 [1,2,1], [1,1,2]Output: false
思路:递归。自顶向下深度优先搜索,递归判断是否是相同的子树,如果元素不同,或者一个有元素一个没有,则不同,如果最后都没有元素,则相同。
/** * 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)||(!q&&p)) return false; if(!p&&!q) return true; return (p->val==q->val&&isSameTree(p->left,q->left)&&isSameTree(p->right,q->right)); }};
阅读全文
0 0
- Leetcode - Tree - Same Tree
- [leetcode][tree] Same Tree
- LeetCode: Same Tree
- LeetCode Same Tree
- [Leetcode] Same Tree
- LeetCode : Same Tree
- [LeetCode] Same Tree
- leetcode 65: Same Tree
- Leetcode 100 Same Tree
- [leetcode] Same Tree
- [LeetCode]Same Tree
- [leetcode]Same Tree
- [Leetcode]Same Tree
- Leetcode: Same Tree
- [LeetCode] Same Tree
- LeetCode-Same Tree
- [leetcode] Same Tree
- LeetCode - Same Tree
- TensorFlow实现中文字体分类(三):模型-VGG16
- GET请求与POST提交的区别
- linux下启动telnet服务器
- spring 工作原理
- 利用HSTS安全协议柔性解决全站HTTPS的兼容性问题
- LeetCode--Same Tree
- Fragment全解析系列(二):正确的使用姿势
- 2017中国北京艺术与框业展览会(AFAEXPO)会刊(参展商名录)
- python(三):Python3—UnicodeEncodeError 'ascii' codec can't encode characters in position 0-1
- 经本地项目上传到gitlab
- 20. 配置可被设定范围
- poj 3254 corn fields (状态压缩dp~)
- Mac brew install hadoop 出现 not linked
- golang map引发的 【fatal error: concurrent map read and map write】问题解决