首页 > 代码库 > [Leetcode] Binary Tree Level Order Traversal II

[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:

在I的基础上倒过来就好。

 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>> ret=new ArrayList<List<Integer>>();13         if(root==null)14             return ret;15         List<List<Integer>> alal=new ArrayList<List<Integer>>();16         List<Integer> al=new ArrayList<Integer>();17         Queue<TreeNode> queue=new LinkedList<TreeNode>();18         queue.add(root);19         int curLevel=1;20         int nextLevel=0;21         22         while(!queue.isEmpty()){23             TreeNode cur=queue.remove();24             al.add(cur.val);25             curLevel--;26             27             if(cur.left!=null){28                 queue.add(cur.left);29                 nextLevel++;30             }31             32             if(cur.right!=null){33                 queue.add(cur.right);34                 nextLevel++;35             }36             37             if(curLevel==0){38                 alal.add(al);39                 al=new ArrayList<Integer>();40                 curLevel=nextLevel;41                 nextLevel=0;42             }43         }44         for(int i=alal.size()-1;i>=0;--i){45             ret.add(alal.get(i));46         }47         48         return ret;49     }50 }

 

[Leetcode] Binary Tree Level Order Traversal II