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