Skip to content

Commit dbf1e8e

Browse files
committed
update md files
update README.md
1 parent 7b8aee8 commit dbf1e8e

20 files changed

+493
-3
lines changed

Notes/Tree 树/100_相同的树.md

Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
2+
3+
# 100 :相同的树
4+
5+
## 📌题目详情
6+
7+
[leetcode 题目地址](https://leetcode.com/problems/same-tree/)
8+
9+
[leetcode-cn 题目地址](https://leetcode-cn.com/problems/same-tree/)
10+
11+
📗Difficulty:**Easy**
12+
13+
🎯Tags:
14+
15+
+ **[](https://leetcode-cn.com/tag/tree/)**
16+
+ **[深度优先搜索](https://leetcode-cn.com/tag/depth-first-search/)**
17+
18+
---
19+
20+
## 📃题目描述
21+
22+
给定两个二叉树,编写一个函数来检验它们是否相同。
23+
24+
如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
25+
26+
27+
28+
**样例 1:**
29+
30+
```
31+
输入: 1 1
32+
/ \ / \
33+
2 3 2 3
34+
35+
[1,2,3], [1,2,3]
36+
37+
输出: true
38+
```
39+
40+
41+
42+
**样例 2:**
43+
44+
```
45+
输入: 1 1
46+
/ \
47+
2 2
48+
49+
[1,2], [1,null,2]
50+
51+
输出: false
52+
```
53+
54+
55+
56+
**样例 3:**
57+
58+
```
59+
输入: 1 1
60+
/ \ / \
61+
2 1 1 2
62+
63+
[1,2,1], [1,1,2]
64+
65+
输出: false
66+
```
67+
68+
69+
70+
****
71+
72+
## 🏹🎯解题思路
73+
74+
> 以下思路来自于 [leetcode-cn 用户 labuladong 的题解](https://leetcode-cn.com/problems/same-tree/solution/xie-shu-suan-fa-de-tao-lu-kuang-jia-by-wei-lai-bu-/),感谢他的详细分析和更多拓展。
75+
76+
本身对 BST 的定义的递归定义的,题目也给出了很详细的递归定义。使用递归来解决是最好的方案。
77+
78+
需要注意 `if` 判断中的几个小细节即可。
79+
80+
81+
82+
#### 代码实现
83+
84+
```java
85+
public boolean isSameTree(TreeNode p, TreeNode q) {
86+
// 都为空的话,显然相同
87+
if (p == null && q == null) {
88+
return true;
89+
}
90+
// 一个为空,一个非空,显然不同
91+
if (p == null || q == null) {
92+
return false;
93+
}
94+
// 两个都非空,但 val 不一样也不行
95+
if (q.val != p.val) {
96+
return false;
97+
}
98+
// 子树,递归的调用进行判断
99+
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
100+
}
101+
```
102+
103+
104+
105+
#### 复杂度分析
106+
107+
+ 时间复杂度:`O(n)` 。每一个节点都要访问一次。
108+
+ 空间复杂度:`O(n)` 。在树退化成单链表的情况下,递归调用栈的大小为 `O(n)`
109+
110+
111+
112+
---
113+
114+
## 💡总结
115+
116+
#### 相似题目
117+
118+
[700. 二叉搜索树中的搜索](https://leetcode-cn.com/problems/search-in-a-binary-search-tree/) 的递归思路的框架和本题很相似。下面给出其代码:
119+
120+
```java
121+
public TreeNode searchBST(TreeNode root, int val) {
122+
if (root == null) {
123+
return null;
124+
}
125+
126+
if (root.val == val) {
127+
return root;
128+
} else if (root.val > val) { // 利用 BST 的特征,去左子树继续查找
129+
return searchBST(root.left, val);
130+
} else {
131+
return searchBST(root.right, val);
132+
}
133+
}
134+
```
135+
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

0 commit comments

Comments
 (0)