zoukankan      html  css  js  c++  java
  • [百度面试题] 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)
    

      

  • 相关阅读:
    数学+高精度 ZOJ 2313 Chinese Girls' Amusement
    最短路(Bellman_Ford) POJ 1860 Currency Exchange
    贪心 Gym 100502E Opening Ceremony
    概率 Gym 100502D Dice Game
    判断 Gym 100502K Train Passengers
    BFS POJ 3278 Catch That Cow
    DFS POJ 2362 Square
    DFS ZOJ 1002/HDOJ 1045 Fire Net
    组合数学(全排列)+DFS CSU 1563 Lexicography
    stack UVA 442 Matrix Chain Multiplication
  • 原文地址:https://www.cnblogs.com/lkprof/p/4918562.html
Copyright © 2011-2022 走看看