設計並實現一個算法,找出二叉樹中某兩個節點的第一個共同祖先。不得將其他的節點存儲在另外的數據結構中。注意:這不一定是二叉搜索樹。
例如,給定如下二叉樹: root = [3,5,1,6,2,0,8,null,null,7,4]
3
/ \
5 1
/ \ / \
6 2 0 8
/ \
7 4
示例 1:
輸入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
輸出: 3
解釋: 節點 5 和節點 1 的最近公共祖先是節點 3。
示例 2:
輸入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
輸出: 5
解釋: 節點 5 和節點 4 的最近公共祖先是節點 5。因爲根據定義最近公共祖先節點可以爲節點本身。
說明:
所有節點的值都是唯一的。
p、q 爲不同節點且均存在於給定的二叉樹中。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/first-common-ancestor-lcci
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
思路:
分別標記p,q是否在不同的樹,若不在同一棵子樹,則返回離它們最近的一個分成左右子樹的節點。若在同一棵樹,則先遍歷到誰就返回誰。
func lowestCommonAncestor(root *TreeNode, p *TreeNode, q *TreeNode) *TreeNode {
if root == nil || root == p || root == q {
return root
}
var l *TreeNode
var r *TreeNode
l = lowestCommonAncestor(root.Left,p,q)
r = lowestCommonAncestor(root.Right,p,q)
//l,r不在同一個子樹則返回離它們最近的分成兩棵子樹的節點
if l != nil && r != nil {
return root
}
//先遍歷到誰就返回誰
if l != nil {
return l
}
if r != nil {
return r
}
//都沒有則返回null
return nil
}