|
1 | | -# [100. xxx](https://leetcode-cn.com/problems/recover-binary-search-tree) |
| 1 | +# [100. 相同的树](https://leetcode-cn.com/problems/same-tree/description/) |
2 | 2 |
|
3 | 3 | ### 题目描述
|
4 | 4 |
|
| 5 | +<p>给定两个二叉树,编写一个函数来检验它们是否相同。</p> |
| 6 | + |
| 7 | +<p>如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。</p> |
| 8 | + |
| 9 | +<p><strong>示例 1:</strong></p> |
| 10 | + |
| 11 | +<pre><strong>输入: </strong> 1 1 |
| 12 | + / \ / \ |
| 13 | + 2 3 2 3 |
| 14 | + |
| 15 | + [1,2,3], [1,2,3] |
| 16 | + |
| 17 | +<strong>输出:</strong> true</pre> |
| 18 | + |
| 19 | +<p><strong>示例 2:</strong></p> |
| 20 | + |
| 21 | +<pre><strong>输入: </strong> 1 1 |
| 22 | + / \ |
| 23 | + 2 2 |
| 24 | + |
| 25 | + [1,2], [1,null,2] |
| 26 | + |
| 27 | +<strong>输出:</strong> false |
| 28 | +</pre> |
| 29 | + |
| 30 | +<p><strong>示例 3:</strong></p> |
| 31 | + |
| 32 | +<pre><strong>输入:</strong> 1 1 |
| 33 | + / \ / \ |
| 34 | + 2 1 1 2 |
| 35 | + |
| 36 | + [1,2,1], [1,1,2] |
| 37 | + |
| 38 | +<strong>输出:</strong> false |
| 39 | +</pre> |
5 | 40 |
|
6 | 41 | ### 解题思路
|
7 | 42 |
|
| 43 | +1. 递归判断 |
8 | 44 |
|
9 | 45 | ### 具体解法
|
10 | 46 |
|
11 | | -<!-- tabs:start --> |
12 | | - |
13 | 47 | #### **Golang**
|
14 | 48 | ```go
|
15 | | - |
| 49 | +type TreeNode struct { |
| 50 | + Val int |
| 51 | + Left *TreeNode |
| 52 | + Right *TreeNode |
| 53 | +} |
| 54 | +func isSameTree(p *TreeNode, q *TreeNode) bool { |
| 55 | + if p == nil && q == nil { |
| 56 | + return true |
| 57 | + } |
| 58 | + if p == nil || q == nil { |
| 59 | + return false |
| 60 | + } |
| 61 | + return p.Val == q.Val && isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right) |
| 62 | +} |
16 | 63 | ```
|
17 | 64 |
|
18 | | -<!-- tabs:end --> |
19 | 65 |
|
0 commit comments