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,null,null,15,7]
,3 / \ 9 20 / \ 15 7return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
二叉树层序遍历二。题意跟版本一很接近,唯一的不同点是输出的output需要从下往上排列,叶子节点层最先输出,根节点在最后输出。
因为跟版本一很接近我就不过多解释思路了,依然是BFS和DFS两种做法。两种做法的时间和空间复杂度均为O(n)。
BFS
JavaScript实现
1 /** 2 * @param {TreeNode} root 3 * @return {number[][]} 4 */ 5 var levelOrderBottom = function (root) { 6 let res = []; 7 if (root === null) return res; 8 let queue = []; 9 queue.push(root); 10 while (queue.length) { 11 let size = queue.length; 12 let list = []; 13 for (let i = 0; i < size; i++) { 14 let cur = queue.shift(); 15 if (cur.left !== null) queue.push(cur.left); 16 if (cur.right !== null) queue.push(cur.right); 17 list.push(cur.val); 18 } 19 res.unshift(list); 20 } 21 return res; 22 };
Java实现
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public List<List<Integer>> levelOrderBottom(TreeNode root) { 12 List<List<Integer>> res = new ArrayList<>(); 13 // corner case 14 if (root == null) { 15 return res; 16 } 17 18 // normal case 19 Queue<TreeNode> queue = new LinkedList<>(); 20 queue.offer(root); 21 while (!queue.isEmpty()) { 22 int size = queue.size(); 23 List<Integer> list = new ArrayList<>(); 24 for (int i = 0; i < size; i++) { 25 TreeNode cur = queue.poll(); 26 list.add(cur.val); 27 if (cur.left != null) { 28 queue.offer(cur.left); 29 } 30 if (cur.right != null) { 31 queue.offer(cur.right); 32 } 33 } 34 res.add(0, list); 35 } 36 return res; 37 } 38 }
DFS
JavaScript实现
1 /** 2 * @param {TreeNode} root 3 * @return {number[][]} 4 */ 5 var levelOrderBottom = function (root) { 6 let res = []; 7 if (root === null) return res; 8 helper(res, root, 0); 9 return res; 10 }; 11 12 var helper = function (res, root, level) { 13 if (root === null) return; 14 if (level >= res.length) { 15 res.unshift([]); 16 } 17 res[res.length - level - 1].push(root.val); 18 helper(res, root.left, level + 1); 19 helper(res, root.right, level + 1); 20 };
相关题目
102. Binary Tree Level Order Traversal
107. Binary Tree Level Order Traversal II