首页 > 其他 > 详细

leetcode-03-二叉树的锯齿层次遍历

时间:2019-07-14 16:35:55      阅读:97      评论:0      收藏:0      [点我收藏+]

题目描述:

技术分享图片

方法一:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root:
            return []
        stack = [root]
        ans = []
        while stack:
            tem_stack=[]
            tem_ans = []
            for i in stack:
                tem_ans.append(i.val)
                if i.left:
                    tem_stack.append(i.left)
                if i.right:
                    tem_stack.append(i.right)
            stack = tem_stack
            ans.append(tem_ans)

        for i in range(len(ans)):
            if i%2!=0:
                ans[i] = ans[i][::-1]
        return ans

另:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root:
            return []
        stack = [root]
        ans = []
        depth = 0
        while stack:
            tem_ans,tem_stack = [],[]
            for i in stack:
                tem_ans.append(i.val)
                if i.left:
                    tem_stack.append(i.left)
                if i.right:
                    tem_stack.append(i.right)
            if depth%2 == 0:
                ans.append(tem_ans)
            else:
                ans.append(tem_ans[::-1])
            stack = tem_stack
            depth += 1
        return ans

方法二:递归

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
        res = []
        def helper(root, depth): 
            if not root: return 
            if len(res) == depth: 
                res.append([]) 
            if depth % 2 == 0:
                res[depth].append(root.val) 
            else: 
                res[depth].insert(0, root.val) 
            helper(root.left, depth + 1) 
            helper(root.right, depth + 1) 
        helper(root, 0) 
        return res

 

leetcode-03-二叉树的锯齿层次遍历

原文:https://www.cnblogs.com/oldby/p/11184361.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!