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] ]
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> reList = new ArrayList<List<Integer>>(); List<List<TreeNode>> nodeList = new ArrayList<List<TreeNode>>(); List<TreeNode> treList = new ArrayList<TreeNode>(); if(root==null) return reList; int i = 0; treList.add(root); nodeList.add(treList); boolean flag = true; while(flag) { flag = false; treList = nodeList.get(i++); List<TreeNode> tempList = new ArrayList<TreeNode>(); for(TreeNode node:treList) { if(node.left!=null) { tempList.add(node.left); flag = true; } if(node.right!=null) { tempList.add(node.right); flag = true; } } if(!tempList.isEmpty()) nodeList.add(tempList); } for(int j = nodeList.size()-1;j>=0;j--) { treList = nodeList.get(j); List<Integer> tempList = new ArrayList<Integer>(); for(TreeNode node:treList) { tempList.add(node.val); } reList.add(tempList); } return reList; } }