LeetCode/solutions/100. Same Tree.md

20 lines
731 B
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [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);
}
};
```