avatar
python里面怎么表示树?# JobHunting - 待字闺中
c*u
1
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
写了一段代码, 但是不知道如何测试.
请问, 在测试的时候, 我知道要用list表示树, 但是具体如何表示
比如, 我要输入一个binary tree,
1
/
2 3
/ /
4 5 6

8
这个数, 要用list如何表示
avatar
j*p
2
'''Create a binary tree from an input list.'''
import math
# If we store a full binary tree using BFS into a list, map the index of the
# node to its parent and which branch this node is.
# node_index parent_index branch
# 1 0 0
# 2 0 1
# 3 1 0
# 4 1 1
# 5 2 0
# ...
def GetParentMap(max_nodes):
parent_map = {} # index: (parent_index, left_or_right)
current_parent = 0
current_branch = 0
for i in range(1, max_nodes):
parent_map[i] = (current_parent, current_branch)
# Switch between left and right
current_branch = 1 - current_branch # left: 0, right: 1
if current_branch == 0:
current_parent += 1
return parent_map
def GenerateTree(input_list):
if not input_list:
return None
max_depth = int(math.ceil(math.log(len(input_list)+1 ,2)))
num_nodes = 2**max_depth - 1
parent_map = GetParentMap(num_nodes)
nodes = [None] * num_nodes # Save nodes in a list for accessing
root = {'v': input_list[0]} # v: value, 0: left_child, 1: right_child
nodes[0] = root
for i in range(1, len(input_list)):
if input_list[i] is None:
continue
parent_idx, branch = parent_map[i]
parent = nodes[parent_idx]
new_node = {'v': input_list[i]}
parent[branch] = new_node # Link the child here.
nodes[i] = new_node
return root
# Print the tree using in-order traversal.
# A leaf node will be followed by 'NL NR'.
def PrintTree(node):
if node:
print node['v'],
if 0 in node:
PrintTree(node[0]),
else:
print 'NL', # No left child
if 1 in node:
PrintTree(node[1]),
else:
print 'NR', # No right child
if __name__ == '__main__':
while True:
# Sample input_list: [1, 2, 3, 4, None, 5, 6, None, 8, None, None]
input_list = input("Input the tree: ")
tree = GenerateTree(input_list)
PrintTree(tree)
print
avatar
w*p
3
just use a list:
[left, value, right]
1
/
2 3
/ / \
4 5 6
becomes:
[ [[None,4,None], 2, None], 1, [[None,5,None],3,[None,6,None]] ]
avatar
j*p
4
dict is even easier:
{0: {0: {1: {'v': 8}, 'v': 4}, 'v': 2}, 1: {0: {'v': 5}, 1: {'v': 6}, 'v': 3
}, 'v': 1}
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。