Open pwstrick opened 4 years ago
107. 二叉树的层次遍历 II
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @return {number[][]} */ var levelOrderBottom = function(root) { if(root == null) return []; const stack = bfs(root); return stack.reverse(); }; function bfs(root) { const stack = [], queue = [root]; while(queue.length) { const len = queue.length; let node, arr = [] for(let i=0; i<len; i++) { node = queue[i]; arr.push(node.val); } stack.push(arr); for(let i=0; i<len; i++) { node = queue.shift(); node.left && queue.push(node.left); node.right && queue.push(node.right); } } return stack; }
107. 二叉树的层次遍历 II