Last active
December 23, 2019 03:17
-
-
Save wangyiyang/b90b3bae203b99454a66f6b7a95efac2 to your computer and use it in GitHub Desktop.
二叉树最近公共父节点: 有一个普通二叉树,AB分别为两个子节点,求AB最近的公共父节点。 #Algorithm #Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# find_common_root.py | |
class TreeNode(): | |
def __init__(self, left, right, val): | |
self.val = val | |
self.left = left | |
self.right = right | |
def getPath(self, root, decNode, array): | |
findResult = False | |
if root is not None: | |
if root == decNode: | |
array.append(root) | |
findResult = True | |
if not findResult and root.left is not None: | |
findResult = self.getPath(root.left, decNode, array) | |
if findResult: | |
array.append(root) | |
if not findResult and root.right is not None: | |
findResult = self.getPath(root.right, decNode, array) | |
if findResult: | |
array.append(root) | |
return array | |
def getCommonRoot(root, a, b): | |
common = None | |
pathA = [] | |
pathB = [] | |
a.getPath(root, a, pathA) | |
b.getPath(root, b, pathB) | |
for nodeA in pathA: | |
for nodeB in pathB: | |
if nodeA == nodeB: | |
common = nodeA | |
break | |
if common is not None: | |
break | |
return common | |
if __name__ == '__main__': | |
g = TreeNode(None, None, 7) | |
f = TreeNode(None, None, 6) | |
e = TreeNode(None, None, 5) | |
d = TreeNode(None, None, 4) | |
c = TreeNode(f, g, 3) | |
b = TreeNode(d, e, 2) | |
a = TreeNode(b, c, 1) | |
test = None | |
test = getCommonRoot(a, b, d) | |
if test is not None: | |
print test.val |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment