原题链接在这里:https://leetcode.com/problems/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,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its bottom-up level order traversal as:

[
  [15,7],
  [9,20],
  [3]
]

题解:

Binary Tree Level Order Traversal相似,只是返过来加链表。每次把item从头加进res中.

Time Complexity: O(n). Space O(n).

AC 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 public class Solution {
11     public List<List<Integer>> levelOrderBottom(TreeNode root) {
12         List<List<Integer>> res = new ArrayList<List<Integer>>();
13         if(root == null){
14             return res;
15         }
16         
17         LinkedList<TreeNode> que = new LinkedList<TreeNode>();
18         que.add(root);
19         int curCount = 1;
20         int nextCount = 0;
21         List<Integer> item = new ArrayList<Integer>();
22         while(!que.isEmpty()){
23             TreeNode cur = que.poll();
24             curCount--;
25             item.add(cur.val);
26             
27             if(cur.left != null){
28                 que.add(cur.left);
29                 nextCount++;
30             }
31             if(cur.right != null){
32                 que.add(cur.right);
33                 nextCount++;
34             }
35             if(curCount == 0){
36                 res.add(0, new ArrayList<Integer>(item));
37                 item = new ArrayList<Integer>();
38                 curCount = nextCount;
39                 nextCount = 0;
40             }
41         }
42         return res;
43     }
44 }

 

相关文章:

  • 2022-12-23
  • 2021-07-03
  • 2022-02-06
  • 2021-10-06
猜你喜欢
  • 2021-09-02
  • 2021-05-21
  • 2021-08-30
  • 2021-11-21
  • 2021-09-12
  • 2022-02-09
  • 2021-12-29
相关资源
相似解决方案