高级农民
- 积分
- 3058
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2011-10-21
- 最后登录
- 1970-1-1
|
"3. 一个 tree, 返回每个 key 之间的路径."
这个题我认为应该是先遍历一遍树,取出来所有的节点值放到一个数组里面,然后对数组做任意两个节点的combination,然后问题就转化为求两个确定的节点之间的路径.
这个代码可以run
- # Python3 program to print path between any
- # two nodes in a Binary Tree
- import sys
- import math
- # structure of a node of binary tree
- class Node:
- def __init__(self, data):
- self.data = data
- self.left = None
- self.right = None
- # Helper function that allocates a new node with the
- # given data and NULL left and right pointers.
- def getNode(data):
- return Node(data)
- # Function to check if there is a path from root
- # to the given node. It also populates
- # 'arr' with the given path
- def _get_path(res, _path, _root, target):
- print("In my get_path")
- if not _root:
- return
- _path.append(_root.data)
- if _root.data == target:
- res.append(_path[:])
- return
- _get_path(res, _path, _root.left, target)
- _get_path(res, _path, _root.right, target)
- _path.pop()
- # Function to print the path between
- # any two nodes in a binary tree
- def printPathBetweenNodes(root, n1, n2):
- # # vector to store the path of
- # # first node n1 from root
- # path1 = []
- # # vector to store the path of
- # # second node n2 from root
- # path2 = []
- # getPath(root, path1, n1)
- # getPath(root, path2, n2)
- my_path1 = []
- my_path2 = []
- _get_path(my_path1, [], root, n1)
- _get_path(my_path2, [], root, n2)
- path1 = my_path1[0]
- path2 = my_path2[0]
- # Get intersection point
- i, j = 0, 0
- intersection = -1
- while (i != len(path1) or j != len(path2)):
- # Keep moving forward until no intersection
- # is found
- if (i == j and path1[i] == path2[j]):
- i += 1
- j += 1
- else:
- intersection = j - 1
- break
- # Print the required path
- for i in range(len(path1) - 1, intersection - 1, -1):
- print("{} ".format(path1[i]), end="")
- for j in range(intersection + 1, len(path2)):
- print("{} ".format(path2[j]), end="")
- # Driver program
- if __name__ == '__main__':
- # binary tree formation
- root = getNode(0)
- root.left = getNode(1)
- root.left.left = getNode(3)
- root.left.left.left = getNode(7)
- root.left.right = getNode(4)
- root.left.right.left = getNode(8)
- root.left.right.right = getNode(9)
- root.right = getNode(2)
- root.right.left = getNode(5)
- root.right.right = getNode(6)
- node1 = 7
- node2 = 6
- printPathBetweenNodes(root, node1, node2)
复制代码 |
|