当前位置:网站首页>235. 二叉搜索樹的最近公共祖先【lca模板 + 找路徑相同】
235. 二叉搜索樹的最近公共祖先【lca模板 + 找路徑相同】
2022-07-03 18:43:00 【白速龍王的回眸】
分析
找到root到p和q的路徑(通過while和大小關系即可)
然後看看兩條路徑最深能到哪裏相同
返回最深的相同的比特置即可
ac code
# 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':
# 找到root到target的path
def get_path(start, target):
now = start
path = []
while now != target:
path.append(now)
# 下一層尋找
if target.val > now.val:
now = now.right
else:
now = now.left
path.append(target)
return path
pa = get_path(root, p)
pb = get_path(root, q)
ans = None
for u, v in zip(pa, pb):
if u == v:
ans = u
else:
break
return ans
總結
lca模板
边栏推荐
- Boost. Asio Library
- Graduation summary
- MySQL duplicate check
- 2022-2028 global physiotherapy clinic industry research and trend analysis report
- leetcode:11. Container with the most water [double pointer + greed + remove the shortest board]
- 042. (2.11) do it when it's time to do it
- Computer graduation design PHP campus address book telephone number inquiry system
- How about the Moco model?
- Administrative division code acquisition
- Zhengda futures news: soaring oil prices may continue to push up global inflation
猜你喜欢
Raft 日志复制
Web3 credential network project galaxy is better than nym?
There are several levels of personal income tax
Add control at the top of compose lazycolumn
2022-2028 global physiotherapy clinic industry research and trend analysis report
The vscode code is automatically modified to a compliance code when it is formatted and saved
Raft log replication
235. The nearest common ancestor of the binary search tree [LCA template + same search path]
组策略中开机脚本与登录脚本所使用的用户身份
Mysql45 lecture learning notes (II)
随机推荐
Naoqi robot summary 27
2022-2028 global aircraft head up display (HUD) industry research and trend analysis report
leetcode:11. Container with the most water [double pointer + greed + remove the shortest board]
235. The nearest common ancestor of the binary search tree [LCA template + same search path]
How to read the source code [debug and observe the source code]
Compose LazyColumn 顶部添加控件
Torch learning notes (5) -- autograd
Why can deeplab v3+ be a God? (the explanation of the paper includes super detailed notes + Chinese English comparison + pictures)
简述服务量化分析体系
Unity2018 to wechat games without pictures
多媒体NFT聚合平台OKALEIDO即将上线,全新的NFT时代或将来临
Administrative division code acquisition
There are several levels of personal income tax
leetcode:556. 下一个更大元素 III【模拟 + 尽可能少变更】
Reappearance of ASPP (atlas spatial pyramid pooling) code
[combinatorics] exponential generating function (properties of exponential generating function | exponential generating function solving multiple set arrangement)
SQL injection -day16
变化是永恒的主题
知其然,而知其所以然,JS 对象创建与继承【汇总梳理】
What does foo mean in programming?