上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
}
};
python3 解法, 执行用时: 28 ms, 内存消耗: 16.6 MB, 提交时间: 2024-02-20 09:43:29
# 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
python3 解法, 执行用时: 40 ms, 内存消耗: 16.7 MB, 提交时间: 2024-02-20 09:43:04
# 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 []
res = []
cur_level = [root]
depth = 0
while cur_level:
tmp = []
next_level = []
for node in cur_level:
tmp.append(node.val)
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
if depth % 2 == 1:
res.append(tmp[::-1])
else:
res.append(tmp)
depth += 1
cur_level = next_level
return res
golang 解法, 执行用时: 0 ms, 内存消耗: 2.4 MB, 提交时间: 2022-08-20 12:04:41
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func zigzagLevelOrder(root *TreeNode) (ans [][]int) {
if root == nil {
return
}
queue := []*TreeNode{root}
for level := 0; len(queue) > 0; level++ {
vals := []int{}
q := queue
queue = nil
for _, node := range q {
vals = append(vals, node.Val)
if node.Left != nil {
queue = append(queue, node.Left)
}
if node.Right != nil {
queue = append(queue, node.Right)
}
}
// 本质上和层序遍历一样,我们只需要把奇数层的元素翻转即可
if level%2 == 1 {
for i, n := 0, len(vals); i < n/2; i++ {
vals[i], vals[n-1-i] = vals[n-1-i], vals[i]
}
}
ans = append(ans, vals)
}
return
}