Depth-first Search -- Leetcode problem100. Same Tree
2017-09-24 09:45
411 查看
描述: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.
分析:判断两棵树是否相等,水题。
思路一:递归遍历。(3ms)
思路二:one line solution (0ms)
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
分析:判断两棵树是否相等,水题。
思路一:递归遍历。(3ms)
class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { if (p == NULL || q == NULL) return (p == q); if (p -> val == q -> val) { return isSameTree(p -> left, q -> left) && isSameTree(p -> right, q -> right); } return false; } };
思路二:one line solution (0ms)
class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { return (p == NULL && q == NULL) || ((q == NULL || p == NULL) && q != NULL && p != NULL) || ((p != NULL && q != NULL) && (p -> val == q -> val) && isSameTree(p->left, q->left) && isSameTree(p->right, q->right)); } };
相关文章推荐
- 图的遍历——深度优先搜索(Depth First Search)
- 图——深度优先搜索(Graph - Depth First Search)
- [leetcode]Depth-first Search-695. Max Area of Island
- 算法入门——深搜(depth first search)小结
- 图的遍历之深度优先搜索(Depth-First Search—DFS)
- LeetCode之Depth-first Search题目汇总
- 深度优先搜索(Depth-First-Search,DFS)
- 深度优先搜索(Depth-First-Search)精髓
- Depth-First-Search(DFS伪代码)
- DFS-深度优先搜索(Depth First Search)—1
- Depth-first Search -- Leetcode problem112. Path Sum
- IDDFS(Iterative deepening depth-first search)的Java实现
- 深度优先搜索DFS(depth first search),拓扑排序
- 图的深度优先搜索(Depth First Search)
- 图的深度优先搜索(Depth First Search,DFS)
- Summary: Depth-first Search(DFS)
- 【算法总结系列-6】深度优先搜索-Depth First Search,DFS
- POJ2225Asteroids![Depth first search]
- Recursive Depth first search graph(adj matrix)
- (Basic algorithm学习笔记)《基础算法四》- 深度优先搜索(Depth First Search,DFS )