题目阐释:

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)

龙仔
12 声望4 粉丝