两个给定节点的最低共同祖先(LCA);使一组值保持零;获得另一组正确的答案
给定二进制搜索树(BST),找到BST中两个给定节点的最低共同祖先(LCA)。
- root = [6,2,8,0,4,7,9,null,null,3,5],p = 2,q = 8; 预期输出= 6;我的输出= 6
- root = [6,2,8,0,4,7,9,null,null,3,5],p = 2,q = 4; 预期输出= 2;我的输出=
使用print
null我正在获取所需值,但是当i 返回
其null时。 我想我在这里缺少一些非常基本的东西。
# 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':
def bst(root,p=p.val,q=q.val):
if not root:
return
if p<root.val and q<root.val:
bst(root.left)
elif p>root.val and q>root.val:
bst(root.right)
else:
return root
return bst(root)
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
- root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8;
expected Output = 6; My output = 6 - root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4;
expected Output = 2; My output = null
On using print
I am getting the required value but when I return
its null.
I think I am missing something very basic here.
# 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':
def bst(root,p=p.val,q=q.val):
if not root:
return
if p<root.val and q<root.val:
bst(root.left)
elif p>root.val and q>root.val:
bst(root.right)
else:
return root
return bst(root)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能需要尝试以下实现:
You may want to try the following implementation: