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 7return its bottom-up level order traversal as:
[ [15,7] [9,20], [3], ]
Java Code:
public List> levelOrderBottom(TreeNode root) { List
> res = new ArrayList
>(); Queue
tmp = new LinkedList (); Stack > res0 = new Stack
>(); if(root == null) return res; tmp.add(root); while(!tmp.isEmpty()){ int size = tmp.size(); List
level = new ArrayList (); for(int i = 0; i < size; i++){ TreeNode node = tmp.poll(); level.add(node.val); if(node.left != null) tmp.add(node.left); if(node.right != null) tmp.add(node.right); } res0.add(level); } while(!res0.isEmpty()){ res.add(res0.pop()); } return res; }
No comments:
Post a Comment