LeetCode-103. 二叉树的锯齿形层序遍历【树 广度优先搜索 二叉树】
- 题目描述:
- 解题思路一:层序遍历,唯一区别就是`ans.append(level[::-1] if len(ans) % 2 else level)`
- 背诵版:
- 解题思路三:0
题目描述:
给你二叉树的根节点 root ,返回其节点值的 锯齿形层序遍历 。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:[[3],[20,9],[15,7]]
示例 2:
输入:root = [1]
输出:[[1]]
示例 3:
输入:root = []
输出:[]
提示:
树中节点数目在范围 [0, 2000] 内
-100 <= Node.val <= 100
解题思路一:层序遍历,唯一区别就是ans.append(level[::-1] if len(ans) % 2 else level)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:if not root:return []queue = deque([root])ans = []while queue:level = []for _ in range(len(queue)):cur = queue.popleft()level.append(cur.val)if cur.left:queue.append(cur.left)if cur.right:queue.append(cur.right)ans.append(level[::-1] if len(ans) % 2 else level)return ans
时间复杂度:O(n)
空间复杂度:O(n)
背诵版:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:if not root:return []q = deque([root])ans = []while q:level = []for i in range(len(q)):cur = q.popleft()level.append(cur.val)if cur.left:q.append(cur.left)if cur.right:q.append(cur.right)# if len(ans) % 2 == 0:# ans.append(level[:])# else:# ans.append(level[::-1])ans.append(level[::-1] if len(ans) % 2 else level[:])return ans
时间复杂度:O(n)
空间复杂度:O(n)
解题思路三:0
时间复杂度:O(n)
空间复杂度:O(n)
♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠