搜尋二叉樹中兩個節點的最近公共祖先
阿新 • • 發佈:2019-01-07
搜尋二叉樹中兩個節點的最近公共祖先
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Given binary search tree: root = [6,2,8,0,4,7,9,null,null,3,5]
思路
二叉樹中的題基本跑不過遍歷,二叉樹中有四種遍歷方式,根據題意應該是從最下面當最上面的過程,所以可以確定遍歷的方法是後序遍歷。
後序遍歷還是採用遞迴的形式描述,既然使用遞迴就需要確定遞迴公式。遞迴公中包含base case,還會告訴我們如何進行遞迴。下面給出遞迴公式:
- 當前為空直接返
- 當前節點是兩個待查詢中的一個直接返回
- 遞迴的查詢左子樹
- 遞迴的查詢右子樹
- 左右子樹都不為空,當前節點就是最近公共祖先,直接返回
- 左右子樹都為空,以當前節點為根節點的BST中不包含,返回空
- 左右子樹有一個為空,一個非空,那麼非空的那個子樹的根節點分兩種情況,可能是待查詢兩個節點的一個,兩種情況這個節點都是兩個節點的最近公共祖先,返回這個節點
程式碼
/** * Definition for TreeNode. * type TreeNode struct { * Val int * Left *ListNode * Right *ListNode * } */ func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { if root == nil || root == p || root == q { return root } left := lowestCommonAncestor(root.Left, p, q) right := lowestCommonAncestor(root.Right, p, q) if left != nil && right != nil { return root } ret := left if left == nil { ret = right } return ret }
對比上述的遞迴公式,把遞迴公式分層三組,(1,2),(3,4)和(5,7)其實就是後序遍歷的框架,1,2是base case,3,4是遞迴,5,6,7是對當前節點的處理。
關於作者
大四學生一枚,分析資料結構,面試題,golang,C語言等知識。QQ交流群:521625004。微信公眾號:後臺技術棧。二維碼如下: