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
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 ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) { ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>(); if(root==null) { return ret; } ArrayList<TreeNode> fronties = new ArrayList<TreeNode>(); fronties.add(root); while(fronties.size()!=0) { ArrayList<Integer> level = new ArrayList<Integer>(); ArrayList<TreeNode> tmp = new ArrayList<TreeNode>(); for(TreeNode frontie : fronties) { level.add(frontie.val); if(frontie.left!=null) tmp.add(frontie.left); if(frontie.right!=null) tmp.add(frontie.right); } ret.add(0, level); fronties = tmp; } return ret; } }
没有评论:
发表评论