題目出處
448 · Inorder Successor in BST
難度
medium
個人範例程式碼 - recursive 版本
"""
Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
"""
class Solution:
"""
@param: root: The root of the BST.
@param: p: You need find the successor node of p.
@return: Successor of p.
"""
def inorderSuccessor(self, root, p):
# write your code here
if not root:
return None
self.found = False
self.ans = None
self.dfs(root, p)
return self.ans
def dfs(self, node, p):
if not node:
return
self.dfs(node.left, p)
if self.found == True: # next node
self.ans = node
self.found = False
if node == p:
self.found = True
self.dfs(node.right, p)
算法說明
inorder 排序的延伸,這裡要先知道 Successor 的定義比較好解
Successor 定義簡單就是:在 inorder 排序下,此 node 的下一個 node。
而討論可能的相對位置 (不清楚可以想一下 inorder 定義)
:
- 如果有右子樹,就是右樹的第一個 node
- 如果沒有右樹,就是往上方的 node 尋找第一個左彎的 node
借一下 BST iterator 的 圖3,相對位置就是 next
不過說實在,這樣還要討論太麻煩了,不如就直接無腦開始 traverse 還比較快XD
這也是我最後的做法,只需要注意修改 inorder 的中間位置,
這邊要增加讀取 val,且發現上一個為 p 時,需要做一下記號。
最近在練習程式碼本身就可以自解釋的 Coding style,可以嘗試直接閱讀程式碼理解
input handling
找不到對應結果時,回傳 -1 (題目沒有要求這部份)
Boundary conditions
x
