首页 » Python » 【leetCode】Binary Tree Zigzag Level Order Traversal python实现

【leetCode】Binary Tree Zigzag Level Order Traversal python实现

2016-06-19 01:40:02阅读(373)

Binary Tree Zigzag Level Order Traversal 原题链接

leetCode.com/problems/binary-tree-zigzag-level-order-traversal/">Binary Tree Zigzag Level Order Traversal

实现原理解析

层次遍历即可,对于偶数层的做反向

python代码实现
import copy
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution(object):
    def __init__(self):
        self.result = []
    def zigzagLevelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if root is None:
            return []
        else:
            rootLevel =[root]
            self.result.append(rootLevel)
            self.levelSearch(rootLevel)
        for i in xrange(len(self.result)):
            if i%2 == 1:
                self.result[i].reverse()
            self.result[i] = [each.val for each in self.result[i]]
        return self.result
    def levelSearch(self, upLevelNodes):
        """
        :param upLevelNodes:
        :return:
        """
        ret = []
        if len(upLevelNodes) == 0:
            self.result.pop()
            return
        for eachNode in upLevelNodes:
            if eachNode.left is not None:
                ret.append(eachNode.left)
            if eachNode.right is not None:
                ret.append(eachNode.right)
        if len(ret) == 0:
            return
        self.result.append(ret)
        self.levelSearch(ret)

最新发布

CentOS专题

关于本站

5ibc.net旗下博客站精品博文小部分原创、大部分从互联网收集整理。尊重作者版权、传播精品博文,让更多编程爱好者知晓!

小提示

按 Ctrl+D 键,
把本文加入收藏夹