# 100. 相同的树

[https://leetcode-cn.com/problems/same-tree/](https://leetcode-cn.com/problems/same-tree/)

## 解法一：

两棵树以相同的路径遍历（前序或后序）

```python
class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        if p and q:     #若p，q都非空，可以前序或后序遍历，只要两棵树遍历路径一致
            if p.val == q.val:    #值相等，则递归左右子树
                return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
            else:
                return False
        elif (p and not q) or (q and not p):  #若p，q有一个空，另一个非空
            return False
        else:    #若p，q均为空
            return True
```

也可以先判断非空，这样p，q一个空一个非空的条件较为简洁

```python
class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        if not p and not q:     
            return True
        elif not p or not q:
            return False
        else:
            if p.val == q.val:
                return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
            else:
                return False
```
