Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Create P06_LCAinBinaryTree.py#42

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
naina024 wants to merge1 commit intoOmkarPathak:master
base:master
Choose a base branch
Loading
fromnaina024:patch-1
Open
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletionsTrees/P06_LCAinBinaryTree.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
# LCA - least common ancestor
# The lowest common ancestor of two nodes n1 and n2 is the lowest node in tree that has both n1 and n2 as descendants.


class node:
def __init__(self,key):
self.key=key
self.left=None
self.right=None

def lca(root,n1,n2):
if root is None:
return None

if root.key == n1 or root.key == n2:
return root

left = lca(root.left, n1, n2)
right = lca(root.right, n1, n2)

if left and right:
return root

return left if left else right


# Consider the following binary tree

# 3
# / \
# 6 8
# / \ \
# 2 11 13
# / \ /
# 9 5 7

# Create binary tree
root=node(3)
l = root.left = node(6)
r = root.right = node(8)
r.right = node(13)
r.right.left = node(7)
l.left = node(2)
l.right = node(11)
l.right.left = node(9)
l.right.right = node(5)

print(lca(root, 2, 5).key) # outputs '6'

[8]ページ先頭

©2009-2025 Movatter.jp