leetcode------Binary Tree Level Order Traversal II

标题: Binary Tree Level Order Traversal II
通过率: 30.5%
难度: 简单

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]

]

 

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

本题与前边我做的题目Binary Tree Level Order Traversal是一模一样的,第一个版本就是把树按层次进行输出,那么本题就是逆序,只用把最后的结果按照头插入法进行插入即可。

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

12          //List<List<Integer>> result=new LinkedList<List<Integer>>();

13         LinkedList<TreeNode> queue=new LinkedList<TreeNode>();

14         LinkedList<List<Integer>> ensort=new LinkedList<List<Integer>>();

15         int count=1,level=0;

16         if(root==null) return ensort;

17         queue.addLast(root);

18         while(!queue.isEmpty()){

19             level=0;

20             List<Integer> tmp=new ArrayList<Integer>();

21             for(int i=0;i<count;i++){

22                 TreeNode tree=queue.removeFirst();

23                 tmp.add(tree.val);

24                 if(tree.left!=null){

25                     queue.addLast(tree.left);

26                     level++;

27                 }

28                 if(tree.right!=null){

29                     queue.addLast(tree.right);

30                     level++;

31                 }

32             }

33             ensort.addFirst(tmp);

34             count=level;

35         }

36         //result=ensort;

37         return ensort;

38     }

39 }

 

你可能感兴趣的:(LeetCode)