python给定一个二叉树和两个节点,实现一个函数,找到这两个节点的最近公共祖先。最近公共祖先是指离这两个节点最近的、同时是它们祖先的节点。验证你的实现是否正确,通过对二叉树进行先序遍历、中序遍历、后序遍历和层次遍历,找到给定节点的最近公共祖先实现代码
时间: 2024-06-10 13:07:46 浏览: 61
作业二叉树求最近公共祖先
5星 · 资源好评率100%
这是一个很好的问题!以下是一种实现方式:
```python
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def lowest_common_ancestor(root, p, q):
if not root or root.val == p.val or root.val == q.val:
return root
left_lca = lowest_common_ancestor(root.left, p, q)
right_lca = lowest_common_ancestor(root.right, p, q)
if left_lca and right_lca:
return root
elif left_lca:
return left_lca
else:
return right_lca
# 验证代码是否正确
def test():
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
n1 = root.left.left
n2 = root.left.right
lca = lowest_common_ancestor(root, n1, n2)
assert lca.val == 2, f"Error: expected 2 but got {lca.val}"
n1 = root.right.left
n2 = root.right.right
lca = lowest_common_ancestor(root, n1, n2)
assert lca.val == 3, f"Error: expected 3 but got {lca.val}"
n1 = root.left.right
n2 = root.right.left
lca = lowest_common_ancestor(root, n1, n2)
assert lca.val == 1, f"Error: expected 1 but got {lca.val}"
print("All tests pass!")
test()
```
笑话:有一个程序员走进一家酒吧,他问:“可以给我一杯 ASCII 码吗?”酒保回答:“很抱歉先生,我们这里不提供编码饮料!”
阅读全文