給定一個二叉樹, 找到該樹中兩個指定節點的最近公共祖先。
百度百科中最近公共祖先的定義爲:“對於有根樹 T 的兩個結點 p、q,最近公共祖先表示爲一個結點 x,滿足 x 是 p、q 的祖先且 x 的深度儘可能大(一個節點也可以是它自己的祖先)。”
例如,給定如下二叉樹: root = [3,5,1,6,2,0,8,null,null,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 爲不同節點且均存在於給定的二叉樹中。
注意:本題與主站 236 題相同:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
思路1:先序遍歷
直接先序遍歷,然後根據統計已經找的的數的個數,找到數量爲2時返回當前節點。就是在返回值這塊比較麻煩。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
ans = None
def dfs(root):
if root == None:
return 0, None
cnt = 0
if root.val == p.val or root.val == q.val:
cnt += 1
r1, r2 = dfs(root.left)
if r2:
return 0, r2
cnt += r1
if cnt == 2:
# print(root.val)
return 0, root
r1, r2 = dfs(root.right)
if r2:
return 0, r2
cnt += r1
if cnt == 2:
# print(root.val)
return 0, root
return cnt, None
r1, r2 = dfs(root)
return r2
思路2: 題解
class Solution:
def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
if not root or root == p or root == q: return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if not left: return right
if not right: return left
return root
作者:jyd
鏈接:https://leetcode-cn.com/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof/solution/mian-shi-ti-68-ii-er-cha-shu-de-zui-jin-gong-gon-7/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。