題目闡釋:
s型列印,重要的是將binary—tree 逐層遍歷,獲取每層的node。
思路:
將樹的遍歷轉化為 壓棧出棧。 每次將列表內的node全部出棧,獲取子元素,然後全部再入棧。 如此反覆迭代
應用:
當樹有層次資訊時候,可以如此操作。
程式碼如下:
class Node(object):
def __init__(self, val):
self.left_node = None
self.right_node = None
self.value = val
class MakeNode(object):
def __init__(self):
pass
def make_series(self, root_val, value_list_in):
root = Node(root_val)
# cur_node=root
cur_nodes = list()
cur_nodes.append(root)
while cur_nodes:
nodes_iters = list()
while cur_nodes:
cur_node = cur_nodes.pop(0)
nodes_iters.append(cur_node)
for node_iter in nodes_iters:
if value_list_in:
values_iter = value_list_in.pop(0)
if values_iter[0]:
node = Node(values_iter[0])
node_iter.left_node = node
cur_nodes.append(node)
if values_iter[1]:
node = Node(values_iter[1])
node_iter.right_node = node
cur_nodes.append(node)
# print(root)
return root
class BinaryTree(object):
def __init__(self):
pass
def stack(self,root):
nodes=[root]
flag=0
while nodes:
nodes_tmp=list()
while nodes:
nodes_tmp.append(nodes.pop(0))
# print(`nodes_tmp==>`,nodes_tmp)
if flag%2==0:
nodes_print=nodes_tmp
else:
nodes_print=nodes_tmp[::-1]
for val_node in nodes_print:
if val_node:
print(val_node.value)
for node_iter in nodes_tmp:
if node_iter:
# print(node_iter.value)
nodes.extend([node_iter.left_node,node_iter.right_node])
flag+=1
if __name__ == `__main__`:
root = 1
values = [[2,3], [4, 5], [6, 7], [8, 9], [10, 11], [12, None], [None, 13]]
mn = MakeNode()
root=mn.make_series(root, values)
bt=BinaryTree()
bt.stack(root)