• Binary Tree Zigzag Level Order Traversal


    # Definition for a  binary tree node
    class TreeNode:
        def __init__(self, x):
            self.val = x
            self.left = None
            self.right = None
    
    class Solution:
        # @param root, a tree node
        # @return a list of lists of integers
        def zigzagLevelOrder(self, root):
            res=[]
            nodes=[]
            nodes.append(root)
            order=1 #表示这一层显示的顺序
    
            while(nodes!=[]):
                level=[]  #存放这一层的val值
                for i in range(len(nodes)):
                    if nodes[i]!=None:
                        level.append(nodes[i].val)
                if level!=[]:
                    if order==1: # 顺序存放
                        res.append(level)
                    else:  # 反序存放
                        antitone_level=[]
                        for j in range(len(level)):
                            antitone_level.append(level[len(level)-1-j])
                        res.append(antitone_level)
                    order=order*(-1)
    
                temp=[]  #将这一层节点的叶节点存放在nodes中
                for i in range(len(nodes)):
                    if nodes[i]!=None:
                        temp.append(nodes[i].left)
                        temp.append(nodes[i].right)
                nodes=temp
    
            print(res)
            return res
    
    if __name__ == '__main__':
        root=TreeNode(3)
        l=TreeNode(9)
        r=TreeNode(20)
        rl=TreeNode(15)
        rr=TreeNode(7)
        root.left=l
        root.right=r
        r.left=rl
        r.right=rr
    
        s=Solution()
        s.zigzagLevelOrder(root)
  • 相关阅读:
    Android 动画-alpha(渐变透明度动画效果)
    Memento(备忘录)
    Mediator(中介者)
    Iterator(迭代器)
    Command(命令)
    Chain of Responsibility(责任链)
    Template Method(模板方法)
    Interpreter(解释器)
    Proxy(代理)
    Flyweight(享元)
  • 原文地址:https://www.cnblogs.com/iois/p/4026155.html
Copyright © 2020-2023  润新知