题目描述:

方法一:

# 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

最新文章

  1. maven项目管理利器
  2. Ztree行政地区树状展示
  3. Gruntjs: grunt-usemin使用心得
  4. RDD分区2GB限制
  5. python基本数据结构-字典-方法
  6. vue中如何不通过路由直接获取url中的参数
  7. [已解决] java.lang.ClassNotFoundException: org.apache.jsp.WEB_002dINF.com.yourproject.test_jsp
  8. 二. Socket用法
  9. 【BZOJ】【1019】【SHOI2008】汉诺塔
  10. NDK(17)让ndk支持完整C++,exception,rtti,
  11. C: Answers to “The C programming language, Edition 2”
  12. R: for installing package 'RODBC'
  13. 将sublimeText添加到鼠标右键菜单栏
  14. Spring Boot中使用Swagger2构建API文档
  15. 介绍maven构建的生命周期
  16. http://codeforces.com/problemset/problem/847/E
  17. 用java编写一个微博登陆页面
  18. socket通信如何处理每次包长度不定问题
  19. Greenplum扩容
  20. h5-音视频标签

热门文章

  1. topjui.core.js
  2. 搞懂这7个Maven问题,带你吊打面试官!
  3. HashMap底层实现原理及面试问题
  4. netty 文件传输
  5. java oop第09章_JDBC02(CRUD操作)
  6. java日期格式汇总
  7. scala入门基础学习
  8. PHP之最长回文串
  9. leetcode-229-求众数②
  10. 【JZOJ6360】最大菱形和(rhombus)