[百度面试题] S型层次遍历树

设计S型层次遍历树的算法,比如根节点是第一层,第二层从左至右遍历,第三层从右至左遍历,第四层再从左至右遍历,以此类推。

利用队列和每层的节点数,思路是记录每层的节点数并把当前层节点放入队列,奇数层从左到右放,偶数层从右到左放。当前层的队列为空表示输出完一层,层数加一。由于要记录的中间变量比较多,我的第一个实现比较复杂。

实现一:

import Queue

class Node(object):
    """docstring for node"""
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

    def s_print_tree(self, root):
        if root==None:
            return
        node_Queue = Queue.Queue()
        tmp_Queue = []
        node_Queue.put(root)
        deepth = 1
        length = 1
        nextlen = 0
        flag = 0
        while not node_Queue.empty():
            if deepth%2==0:
                if flag==0:
                    while not node_Queue.empty():
                        tmp_Queue.append(node_Queue.get())
                    while tmp_Queue:
                        node_Queue.put(tmp_Queue.pop())
                    flag = 1
                node = node_Queue.get()
                print node.value
                length -= 1
                if node.left!=None:
                    node_Queue.put(node.left)
                    nextlen += 1
                if node.right!=None:
                    node_Queue.put(node.right)
                    nextlen += 1
            else:
                if flag==0:
                    while not node_Queue.empty():
                        tmp_Queue.append(node_Queue.get())
                    while tmp_Queue:
                        node_Queue.put(tmp_Queue.pop())
                    flag = 1
                node = node_Queue.get()
                print node.value
                length -= 1
                if node.right!=None:
                    node_Queue.put(node.right)
                    nextlen += 1
                if node.left!=None:
                    node_Queue.put(node.left)
                    nextlen += 1

            if length==0:
                deepth += 1
                length = nextlen
                nextlen = 0
                flag = 0


if __name__ == '__main__':
    tree = Node('D',Node('B',Node('A'),Node('C')),Node('E',right=Node('G',Node('F'), Node('H'))))
    tree.s_print_tree(tree)

  实现二,利用栈来实现,但发现python基本数据结构中竟然没有栈,只有队列。然而python的队列不仅仅是一个先进先出的数据结构,python的队列是线程安全的,可以应用于多线程程序。如果仅仅为了用队列先进先出的和栈的先进后出性质,用队列就可以了,不必再导入Queue模块。

实现二:

import Queue

class Node(object):
    """docstring for node"""
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

    def s_print_tree(self, root):
        if root==None:
            return
        node_Queue = []
        next_Queue = []
        node_Queue.append(root)
        deepth = 1
        while len(node_Queue)!=0 or len(next_Queue)!=0:
            if len(node_Queue)!=0:
                if deepth%2==0:
                    node = node_Queue[-1]
                    if node.left!=None:
                        next_Queue.append(node.left)
                    if node.right!=None:
                        next_Queue.append(node.right)
                    print node_Queue[-1].value
                    del node_Queue[-1]

                else:
                    node = node_Queue[-1]
                    if node.right!=None:
                        next_Queue.append(node.right)
                    if node.left!=None:
                        next_Queue.append(node.left)
                    print node_Queue[-1].value
                    del node_Queue[-1]


            else:
                node_Queue = next_Queue
                next_Queue = []
                deepth += 1



if __name__ == '__main__':
    tree = Node('D',Node('B',Node('A'),Node('C')),Node('E',right=Node('G',Node('F'), Node('H'))))
    tree.s_print_tree(tree)

  

posted @ 2015-10-28 20:35  lkprof  阅读(787)  评论(0编辑  收藏  举报