二叉树的层序遍历 II
- https://leetcode.cn/problems/binary-tree-level-order-traversal-ii/description/
描述
- 给你二叉树的根节点 root ,返回其节点值 自底向上的层序遍历 。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
示例 1
输入:root = [3,9,20,null,null,15,7]
输出:[[15,7],[9,20],[3]]
示例 2
输入:root = [1]
输出:[[1]]
示例 3
输入:root = []
输出:[]
提示
- 树中节点数目在范围 [0, 2000] 内
- -1000 <= Node.val <= 1000
Typescript 版算法实现
1 ) 方案1: 广度优先搜索
/*** Definition for a binary tree node.* class TreeNode {* val: number* left: TreeNode | null* right: TreeNode | null* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {* this.val = (val===undefined ? 0 : val)* this.left = (left===undefined ? null : left)* this.right = (right===undefined ? null : right)* }* }*//*** Definition for a binary tree node.* class TreeNode {* val: number* left: TreeNode | null* right: TreeNode | null* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {* this.val = (val===undefined ? 0 : val)* this.left = (left===undefined ? null : left)* this.right = (right===undefined ? null : right)* }* }*/function levelOrderBottom(root: TreeNode | null): number[][] {let levelOrder: number[][] = [];if (root === null) return levelOrder;let queue: TreeNode[] = [root];while (queue.length > 0) {let level: number[] = [];let size = queue.length;for (let i = 0; i < size; i++) {let node = queue.shift()!;level.push(node.val);if (node.left !== null) queue.push(node.left);if (node.right !== null) queue.push(node.right);}levelOrder.unshift(level); // Insert at the beginning to reverse order.}return levelOrder;
}
2 ) 方案2: 广度优先搜索
/*** Definition for a binary tree node.* class TreeNode {* val: number* left: TreeNode | null* right: TreeNode | null* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {* this.val = (val===undefined ? 0 : val)* this.left = (left===undefined ? null : left)* this.right = (right===undefined ? null : right)* }* }*/function dfs(node: TreeNode | null, level: number, levels: number[][]): void {if (node === null) return;if (level === levels.length) levels.push([]);levels[level].push(node.val);dfs(node.left, level + 1, levels);dfs(node.right, level + 1, levels);
}function levelOrderBottom(root: TreeNode | null): number[][] {const levels: number[][] = [];dfs(root, 0, levels);return levels.reverse();
}