-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path701.py
82 lines (57 loc) · 1.75 KB
/
701.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# leetcode 701 二叉搜索树中的插入操作
## 迭代法
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root:
node = TreeNode(val)
return node
cur = root
pre = root
while cur:
pre = cur
if val > cur.val:
cur = cur.right
else:
cur = cur.left
node = TreeNode(val=val)
if pre.val < val:
pre.right = node
else:
pre.left = node
return root
## 递归法
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def __init__(self):
self.pre = None
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root:
node = TreeNode(val=val)
return node
self.pre = TreeNode(0)
self.trans(root, val)
return root
def trans(self, root, val):
if not root:
node = TreeNode(val=val)
if val > self.pre.val:
self.pre.right = node
else:
self.pre.left = node
return
self.pre = root
if val > root.val:
self.trans(root.right, val)
if val < root.val:
self.trans(root.left, val)