Leetcode 100. Same Tree
来源:互联网 发布:免费音乐广告制作软件 编辑:程序博客网 时间:2024/05/21 22:25
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.
s思路:
1. 先用recursive.树相等,即:对每个节点值相等,且左子树、右子树都想等,则树相等。你看,我们每次都是把一个实际的问题最后都回归到遍历树的每个节点来,不要被实际问题的花样给吓住了!
2. 这个题用iterative还不好下手。看了自己以前做的,意识到自己以及把iterative和stack等同起来了,而实际上,iterative可以用stack,也可以用queue,对树而言,如果要dfs,则stack,方便在不同的层次见跳转,而queue则是方便一层一层的遍历数,即:bfs。这题,要比较树,把指针一层一层放入queue比较。比较queue中数的个数和值是否一一对应。
3. 顾虑是:先放入再判断,还是先判断再放入?自己做的方法2是先放入,取出的时候即可再判断是否结构和数字都相等。
4. 除了比较值,还需要比较结构!比如:节点值都相等,但是一个有左孩子,一个没有,这种结构就不行!不过由于queue存储的是指针,所以结构不对等,一个有指针,一个指针是空,也可以比较得到!!
//方法1:recursiveclass Solution {public: bool isSameTree(TreeNode* p, TreeNode* q) { // if(!p&&!q) return true; return p&&q&&p->val==q->val&&isSameTree(p->left,q->left)&&isSameTree(p->right,q->right) ; }};//方法2:iterative:queueclass Solution {public: bool isSameTree(TreeNode* p, TreeNode* q) { // queue<TreeNode*> pp,qq; pp.push(p); qq.push(q); while(!pp.empty()||!qq.empty()){ TreeNode* cur_p=pp.front(); TreeNode* cur_q=qq.front(); pp.pop(); qq.pop(); if(!cur_p&&cur_q||cur_p&&!cur_q||cur_p&&cur_q&&cur_p->val!=cur_q->val) return false; if(cur_p&&cur_q&&cur_p->val==cur_q->val){ pp.push(cur_p->left);//先存指针,再取出来比较 pp.push(cur_p->right); qq.push(cur_q->left); qq.push(cur_q->right); } } return true; }};
0 0
- [LeetCode]100.Same Tree
- LeetCode 100. Same Tree
- 【LeetCode】100.Same Tree
- [Leetcode] 100. Same Tree
- [Leetcode] 100. Same Tree
- LeetCode --- 100. Same Tree
- LeetCode 100. Same Tree
- [leetcode] 100.Same Tree
- leetCode 100. Same Tree
- [LeetCode]100. Same Tree
- 100. Same Tree LeetCode
- LeetCode 100. Same Tree
- LeetCode 100. Same Tree
- [LeetCode]100. Same Tree
- 【LeetCode】100. Same Tree
- leetcode 100. Same Tree
- leetcode 100. Same Tree
- 【Leetcode】100. Same Tree
- 51NOD 1060 最复杂的数 【反素数】
- Leetcode 151. Reverse Words in a String
- 196UVa电子表格
- <Python初学>Python中的变量类型。对赋值、浅拷贝与深拷贝的初步认识。
- Leetcode 98. Validate Binary Search Tree
- Leetcode 100. Same Tree
- COVER王锐大大——最长的一帧(第四日)
- Leetcode 101. Symmetric Tree
- Python轻松入门-09 Range函数和While循环
- Leetcode 43. Multiply Strings
- Rails:Ubuntu下连接Git提示Permission denied的解决方法
- [python]mac安装virtualenv
- callee caller
- 开发板串口连接