程式碼隨想錄演算法訓練營第22天 |二叉樹part07:235. 二叉搜尋樹的最近公共祖先、701.二叉搜尋樹中的插入操作、450.刪除二叉搜尋樹中的節點
235.二叉搜尋樹的最近公共祖先
https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/description/
程式碼隨想錄:
https://programmercarl.com/0235.二叉搜尋樹的最近公共祖先.html
701.二叉搜尋樹中的插入操作
https://leetcode.cn/problems/insert-into-a-binary-search-tree/description/
程式碼隨想錄:
https://programmercarl.com/0701.二叉搜尋樹中的插入操作.html
701.二叉搜尋樹中的插入操作
https://leetcode.cn/problems/delete-node-in-a-bst/description/
450.刪除二叉搜尋樹中的節點
https://programmercarl.com/0450.刪除二叉搜尋樹中的節點.html#演算法公開課
235.二叉搜尋樹的最近公共祖先
題解思路
- 遞迴法 利用二叉搜尋樹的特性 將root.val和p.val和q.val對比 如果屬於一邊 就搜尋該邊 否則 就是返回該node
- 迭代:滿足條件就順邊找,不滿足條件就直接跳出;
題解程式碼
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root:
return None
if root.val>q.val and root.val>p.val:
return self.lowestCommonAncestor(root.left,p,q)
elif root.val<p.val and root.val <q.val:
return self.lowestCommonAncestor(root.right,p,q)
else:
return root
```python
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
while root:
if root.val <p.val and root.val<q.val:
root = root.right
elif root.val>q.val and root.val>p.val:
root = root.left
else:
return root
return None
701.二叉搜尋樹中的插入操作
題解思路
- 遞迴法:如果小於val,插入左邊;如果大於val,插入右邊;
- 迭代法:找到需要插入的根節點,直接在根節點插入;
題解程式碼
class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root:
node = TreeNode(val)
return node
if root.val>val:
root.left = self.insertIntoBST(root.left,val)
else:
root.right = self.insertIntoBST(root.right,val)
return root
class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root:
node = TreeNode(val)
return node
curr = root
pre = None
while curr:
pre = curr
if curr.val > val:
curr = curr.left
else:
curr = curr.right
node = TreeNode(val)
if val<pre.val:
pre.left = node
else:
pre.right = node
return root
450.刪除二叉搜尋樹中的節點
題解思路:
- 根據二叉搜尋樹的性質;判斷哪個子樹需要刪除;
- 遇到需要刪除的節點:
- 無左子樹;
- 無右子樹;
- 左右子樹都有;
題解程式碼:
class Solution:
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
if not root:
return root
if root.val==key:
if not root.right:
return root.left
elif not root.left:
return root.right
else:
curr = root.right
while curr.left:
curr = curr.left
curr.left = root.left
return root.right
elif root.val>key:
root.left = self.deleteNode(root.left,key)
else:
root.right = self.deleteNode(root.right,key)
return root