學習資料:https://programmercarl.com/0235.二叉搜尋樹的最近公共祖先.html****
學習記錄:
235.二叉搜尋樹的最近公共祖先(加一個函式traversal)
點選檢視程式碼
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def traversal(self, cur, p, q):
if cur is None:
return cur
if cur.val > p.val and cur.val > q.val:
left = self.traversal(cur.left, p, q)
if left is not None:
return left
if cur.val < p.val and cur.val < q.val:
right = self.traversal(cur.right, p, q)
if right is not None:
return right
return cur
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
return self.traversal(root, p, q)
701.二叉搜尋樹中的插入操作(遞迴法,返回root;根據左<根<右的規則,先左再右子樹的遍歷)
點選檢視程式碼
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def insertIntoBST(self, root, val):
"""
:type root: Optional[TreeNode]
:type val: int
:rtype: Optional[TreeNode]
"""
if not root:
node = TreeNode(val)
return node
if root.val > val:
root.left = self.insertIntoBST(root.left, val)
if root.val < val:
root.right = self.insertIntoBST(root.right, val)
return root
450.刪除二叉搜尋樹中的節點(情況很多,要仔細考慮;用返回值來代替刪除過程;刪除根節點、刪除左子樹上的節點、或者刪除右子樹上的節點,後兩種直接遞迴)
點選檢視程式碼
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def deleteNode(self, root, key):
"""
:type root: Optional[TreeNode]
:type key: int
:rtype: Optional[TreeNode]
"""
# 如果root為空,就返回root
if root is None:
return root
# 刪除根節點的4種情況:都是透過返回值的形式達到刪除節點的目的
if root.val == key:
# 1:二叉樹就一個根節點,那就返回空
if not root.left and not root.right:
return None
# 2:根節點只有右子樹,就返回右子樹
elif not root.left:
return root.right
# 3:根節點只有左子樹,就返回左子樹
elif not root.right:
return root.left
# 4:根節點有左和右子樹,因為滿足左<根<右的條件,在右子樹的某個左節點(該左節點沒有左子樹)下接左子樹。
else:
cur = root.right
while cur.left is not None:
cur = cur.left
cur.left = root.left
return root.right
# 當待刪除的節點非根節點時,用遞迴法
if root.val < key:
root.right = self.deleteNode(root.right, key)
if root.val > key:
root.left = self.deleteNode(root.left, key)
return root
PS:今天有點疲憊了,簡單學了一遍,也沒聽太懂,比較喜歡新增和刪除節點這種題。
今天吃了豬肘飯,不合胃口,配菜倒挺香
馬上迎來週末了!腦子都快裝不下了 哈哈哈