前序/中序/后序遍历属于 深度优先遍历
广度优先遍历实现
节点定义
/*** Definition for a binary tree node.* function TreeNode(val) {* this.val = val;* this.left = this.right = null;* }*/
对应lc 102题
注意js里面 push pop unshift shift之间的区别和关系
// 递归let letOrder = (root) => {if (!root) return []let res = []let helpFunc = (node, level) => {if(!node) return if (res[level] === undefined) {res[level] = []} else {res[level].push(node.val)}helpFunc(node.left, level + 1)helpFunc(node.right, level + 1)}helpFunc(root, 0)return res}
非递归方式
var levelOrderBottom = function(root) {if (!root) return []let res = []let queue = []queue.push(root)while(queue.length > 0) {let len = queue.lengthlet arr = []for (let i = 0; i < len; i++) {let n = queue.pop()arr.push(n.val)if (n.left) queue.unshift(n.left)if (n.right) queue.unshift(n.right)}res.push(arr) }return res
}