100. Same Tree (DFS)
来源:互联网 发布:湖北广电网络客服电话 编辑:程序博客网 时间:2024/06/09 15:52
1. Description
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.
2. Analysis
这样的比较无疑是要逐一对比的,所以每一个节点都会遍历到。可以适当做出一些小技巧来判断特殊情况,减少不必要的运算,比如,在遍历前判断根节点的情况等。本算法设计的思路很简单,就是逐层从左到右比较。
3. Algorithm achievement
/** * 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 == NULL && q == NULL) return true; if(p == NULL || q == NULL) return false; if(p->val != q->val) return false; queue<TreeNode*> T1, T2; T1.push(p); T2.push(q); TreeNode * tmp1 = NULL, *tmp2 = NULL; while(!T1.empty() && !T2.empty()) { if(T1.size() != T2.size()) return false; for(int i = 0, n = T1.size(); i < n; i++) { tmp1 = T1.front(); tmp2 = T2.front(); T1.pop(); T2.pop(); if(tmp1->val != tmp2->val) return false; if((tmp1->left != NULL && tmp2->left == NULL) || (tmp1->left == NULL && tmp2->left != NULL)) { return false; } if((tmp1->right != NULL && tmp2->right == NULL) || (tmp1->right == NULL && tmp2->right != NULL)) { return false; } if(tmp1->left != NULL && tmp2->left != NULL) { T1.push(tmp1->left); T2.push(tmp2->left); } if(tmp1->right != NULL && tmp2->right != NULL) { T1.push(tmp1->right); T2.push(tmp2->right); } } } return true; } };
4. 复杂度分析
意料之中,耗时相对其他解法还存在改进的空间。(待优化)
改进:
注意:不要使用尾递归。
class Solution {public: bool isSameTree(TreeNode* p, TreeNode* q) { if(p == NULL && q == NULL) return true; if(p == NULL || q == NULL) return false; if(p->val != q->val) return false; if (isSameTree(p->left, q->left) && isSameTree(p->right, q->right)) return true; return false; } };
阅读全文
0 0
- 100. Same Tree (DFS)
- DFS:100. Same Tree
- 【Leetcode】100. Same Tree 【DFS】
- [DFS] leetcode 100. Same Tree
- LeetCode oj 100. Same Tree (DFS||BFS)
- 100:Same Tree【树】【DFS】
- leetcode 100. Same Tree 二叉树DFS深度优先遍历
- 【LeetCode】100. Same Tree(水)
- Leetcode:100. Same Tree (JAVA)
- LeetCode 100. Same Tree 题解(C++)
- LeetCode 100. Same Tree(二叉树)
- [LeetCode]100.Same Tree
- LeetCode 100. Same Tree
- 100.Same Tree
- 【LeetCode】100.Same Tree
- [Leetcode] 100. Same Tree
- [Leetcode] 100. Same Tree
- LeetCode --- 100. Same Tree
- HttpClient4.X 解决POST请求返回重定向问题
- nginx服务器高并发优化思路
- Spark体系概况
- springboot报错(三) webjars被拦截或找不到
- shell脚本基础
- 100. Same Tree (DFS)
- 以sqlserver处理父子级关系查询为列介绍with as、cast()、for xml path()、stuff()的使用
- CentOs7 自动获取IP地址图文详解
- 《Python核心编程习题》---chapte11
- 悬浮框计算器
- 日常小结篇-static/final
- JS实现的base64加密、md5加密及sha1加密详解
- 严重: Exception sending context initialized event to listener instance of class [org.springframework.w
- QT no such slot...