107. 二叉树的层序遍历 II
给定一个二叉树,返回其节点值自底向上的层序遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
链接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| function levelOrderBottom(root: TreeNode | null): number[][] { if (root === null) return [] const nodeList: Array<TreeNode | null> = [root] const res = [] while(nodeList.length > 0) { if (nodeList.length === 1) { const parent = nodeList.shift() nodeList.push(parent.left) nodeList.push(parent.right) res.unshift([parent.val]) } else { const nodeL = nodeList.splice(0) const len = nodeL.length const valList = [] for(let i = 0; i < len;i++) { const node = nodeL[i] if (node) { valList.push(node.val) nodeList.push(node.left) nodeList.push(node.right) } } valList.length > 0 && res.unshift(valList) } } return res }
|