跳至主要內容

103. 二叉树的锯齿形层序遍历


103. 二叉树的锯齿形层序遍历

🟠   🔖  广度优先搜索 二叉树  🔗 力扣open in new window LeetCodeopen in new window

题目

Given the root of a binary tree, return the zigzag level order traversal of its nodes ' values. (i.e., from left to right, then right to left for the next level and alternate between).

Example 1:

Input: root = [3,9,20,null,null,15,7]

Output: [[3],[20,9],[15,7]]

Example 2:

Input: root = [1]

Output: [[1]]

Example 3:

Input: root = []

Output: []

Constraints:

  • The number of nodes in the tree is in the range [0, 2000].
  • -100 <= Node.val <= 100

题目大意

按照 Z 字型层序遍历一棵树。

解题思路

这题和 第 102 题 二叉树的层序遍历 几乎是一样的,只要根据层数控制遍历方向即可。

代码

广度优先遍历(BFS)
// 思路一:广度优先遍历(BFS)
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var zigzagLevelOrder = function (root) {
	let res = [];
	if (root == null) return res;
	let queue = [root];
	let flag = true;
	while (queue.length) {
		let len = queue.length;
		let temp = [];
		for (let i = 0; i < len; i++) {
			if (queue[i].left) queue.push(queue[i].left);
			if (queue[i].right) queue.push(queue[i].right);
			if (flag) {
				temp.push(queue[i].val);
			} else {
				temp.unshift(queue[i].val);
			}
		}
		flag = !flag;
		queue = queue.slice(len);
		res.push(temp);
	}
	return res;
};

相关题目

题号标题题解标签难度力扣
102二叉树的层序遍历[✓] 广度优先搜索 二叉树🟠🀄️open in new window 🔗open in new window