mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 100. Same Tree.md
This commit is contained in:
parent
b8de092331
commit
27f86de133
19
100. Same Tree.md
Normal file
19
100. Same Tree.md
Normal file
@ -0,0 +1,19 @@
|
||||
# [100. Same Tree](https://leetcode.com/problems/same-tree/description/)
|
||||
# 思路
|
||||
判断两棵树是否完全相同。最简单的思路就是递归算法,两棵树非空树完全相同的充要条件是:
|
||||
* 根的值相同;
|
||||
* 且左子树和右子树都是分别完全相同的。
|
||||
|
||||
当然也可以考虑遍历两棵树直到遇到不相同的节点即可返回false,若同时遍历完则返回true。
|
||||
|
||||
# C++
|
||||
``` C++
|
||||
class Solution {
|
||||
public:
|
||||
bool isSameTree(TreeNode* p, TreeNode* q) {
|
||||
if(p == NULL && q==NULL) return true; // 都是空树
|
||||
if(p == NULL || q == NULL || (p -> val != q -> val)) return false;
|
||||
return isSameTree(p -> left, q -> left) && isSameTree(p -> right, q -> right);
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in New Issue
Block a user