1. 程式人生 > >LeetCode 第107題 二叉樹的層次遍歷II

LeetCode 第107題 二叉樹的層次遍歷II

ever search ray rbo col ons nod arr lis

給定一個二叉樹,返回其節點值自底向上的層次遍歷。 (即按從葉子節點所在層到根節點所在的層,逐層從左向右遍歷)
例如:
給定二叉樹 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其自底向上的層次遍歷為:
[
[15,7],
[9,20],
[3]
]

思路: 先遞歸層次遍歷
然後將res倒置
 1 class Solution107 {
 2 
 3   List<List<Integer>> res = new ArrayList<>();
 4 
 5   public
List<List<Integer>> levelOrderBottom(TreeNode root) { 6 search(root, 1); 7 Collections.reverse(res); //倒置 8 return res; 9 } 10 11 private void search(TreeNode root, int depth) { 12 if (root != null) { 13 if (res.size() < depth) { 14 res.add(new
ArrayList<>()); 15 } 16 res.get(depth - 1).add(root.val); 17 search(root.left, depth + 1); //搜索左子樹 18 search(root.right, depth + 1); //搜索右子樹 19 } 20 } 21 }

LeetCode 第107題 二叉樹的層次遍歷II