码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 第107题 二叉树的层次遍历II

时间:2019-03-17 15:43:59      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:mil   order   return   自底向上   node   span   pre   lis   soft   

给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [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

标签:mil   order   return   自底向上   node   span   pre   lis   soft   

原文地址:https://www.cnblogs.com/rainbow-/p/10547092.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!