Create 100. Same Tree.md

This commit is contained in:
唐树森 2018-10-31 21:03:51 +08:00 committed by GitHub
parent b8de092331
commit 27f86de133
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

19
100. Same Tree.md Normal file
View 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);
}
};
```