Skip to content

Commit ed4b249

Browse files
authored
Merge pull request doocs#123 from Mrtj2016/dev
add the solution of problem 0701-python.
2 parents 983ad50 + cc60902 commit ed4b249

File tree

2 files changed

+129
-0
lines changed

2 files changed

+129
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
## 二叉搜索树中的插入操作
2+
### 题目描述
3+
4+
给定二叉搜索树(BST)的根节点和要插入树中的值,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 保证原始二叉搜索树中不存在新值。
5+
6+
注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回任意有效的结果。
7+
8+
**示例 :**
9+
```
10+
给定二叉搜索树:
11+
12+
4
13+
/ \
14+
2 7
15+
/ \
16+
1 3
17+
18+
和 插入的值: 5
19+
```
20+
你可以返回这个二叉搜索树:
21+
```
22+
4
23+
/ \
24+
2 7
25+
/ \ /
26+
1 3 5
27+
```
28+
或者这个树也是有效的:
29+
```
30+
5
31+
/ \
32+
2 7
33+
/ \
34+
1 3
35+
\
36+
4
37+
```
38+
39+
### 解法一
40+
返回第一种类型。遍历每个节点,若节点值大于插入值,搜索其左子节点,若小于插入值,则搜索其右子节点。若其节点不存在,则该位置为需要插入的值所在节点。使用递归会使运行时间相对增加,而循环语句的运行更快。
41+
42+
43+
```python
44+
class Solution:
45+
def insertIntoBST(self, root, val):
46+
if not root:
47+
return TreeNode(val)
48+
if root.val < val:
49+
if root.right:
50+
self.insertIntoBST(root.right, val)
51+
else:
52+
root.right = TreeNode(val)
53+
if root.val > val:
54+
if root.left:
55+
self.insertIntoBST(root.left, val)
56+
else:
57+
root.left = TreeNode(val)
58+
return root
59+
```
60+
61+
### 解法二(无法AC)
62+
返回第二种类型。先将根节点替换为插入值,再将根节点的值放到其左子节点中的最右子节点。但是这种解法无法AC,个人认为是题目并不支持返回第二种类型的结果。
63+
64+
```python
65+
class Solution:
66+
def insertIntoBST(self, root, val):
67+
if not root:
68+
return TreeNode(val)
69+
elif root.left is None:
70+
root.left = TreeNode(root.val)
71+
root.val = val
72+
root.val, val = val, root.val
73+
node = root.left
74+
while node.right:
75+
node = node.right
76+
node.right = TreeNode(val)
77+
return root
78+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, x):
4+
# self.val = x
5+
# self.left = None
6+
# self.right = None
7+
8+
# 解法一
9+
class Solution:
10+
def insertIntoBST(self, root, val):
11+
"""
12+
:type root: TreeNode
13+
:type val: int
14+
:rtype: TreeNode
15+
"""
16+
if not root:
17+
return TreeNode(val)
18+
if root.val < val:
19+
if root.right:
20+
self.insertIntoBST(root.right, val)
21+
else:
22+
root.right = TreeNode(val)
23+
if root.val > val:
24+
if root.left:
25+
self.insertIntoBST(root.left, val)
26+
else:
27+
root.left = TreeNode(val)
28+
return root
29+
30+
31+
"""
32+
# 解法二
33+
class Solution:
34+
def insertIntoBST(self, root, val):
35+
"""
36+
: type root: TreeNode
37+
: type val: int
38+
: rtype: TreeNode
39+
"""
40+
if not root:
41+
return TreeNode(val)
42+
elif root.left is None:
43+
root.left = TreeNode(root.val)
44+
root.val = val
45+
root.val, val = val, root.val
46+
node = root.left
47+
while node.right:
48+
node = node.right
49+
node.right = TreeNode(val)
50+
return root
51+
"""

0 commit comments

Comments
 (0)