LeetCode - 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],

]

Solution:

 1 /**

 2  * Definition for binary tree

 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 ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {

12         // Start typing your Java solution below

13         // DO NOT write main() function

14         

15         ArrayList<ArrayList<Integer>> result = new  ArrayList<ArrayList<Integer>>();

16         LinkedList<TreeNode> currLevel = new LinkedList<TreeNode>();

17         

18         int level = 0;

19         if(root != null) currLevel.add(root);

20         while(!currLevel.isEmpty()){

21             LinkedList<TreeNode> nextLevel = new LinkedList<TreeNode>();

22             ArrayList<Integer> list = new ArrayList<Integer>();

23             for(TreeNode n : currLevel){

24                 list.add(n.val);

25                 if(n.left != null){

26                     nextLevel.add(n.left);

27                 }

28                 if(n.right != null){

29                     nextLevel.add(n.right);

30                 }

31             }

32             currLevel = nextLevel;

33             result.add(list);

34             level++;

35         }

36         Collections.reverse(result);

37         return result;

38     }

39 }

 

你可能感兴趣的:(LeetCode)