[LeetCode][JavaScript]Binary Tree Level Order Traversal II

Binary Tree Level Order Traversal II

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   / 
  9  20
    /  
   15   7

return its bottom-up level order traversal as:

[
  [15,7],
  [9,20],
  [3]
]
https://leetcode.com/problems/binary-tree-level-order-traversal-ii/
 
 
 
 

 
 
 
与上一题一样的思路,区别就是最后加入结果的时候往前加。
 
 1 /**
 2  * Definition for a binary tree node.
 3  * function TreeNode(val) {
 4  *     this.val = val;
 5  *     this.left = this.right = null;
 6  * }
 7  */
 8 /**
 9  * @param {TreeNode} root
10  * @return {number[][]}
11  */
12 var levelOrderBottom = function(root) {
13     var res = [], queue = [root];
14     traversal();
15     return res;
16 
17     function traversal(){
18         var top, len = queue.length, subRes = [];
19         while(len--){
20             top = queue.shift();
21             if(top !== null && top.val !== undefined){
22                 subRes.push(top.val);
23                 queue.push(top.left);
24                 queue.push(top.right);
25             }
26         }
27         if(subRes.length > 0){
28             res.unshift(subRes);
29         }
30         if(queue.length > 0){
31             traversal();
32         }
33     }
34 };
 
 
 
原文地址:https://www.cnblogs.com/Liok3187/p/4927472.html