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]
]
public List
> levelOrderBottom(TreeNode root) {
List> result=new ArrayList>();
if(root==null)
return result;
List preelement=new ArrayList();
preelement.add(root);
Stack> stack=new Stack();
stack.push(preelement);
//把每层非空的取出来
while(true){
List nowelement=new ArrayList();
boolean isFinish=false;
for(TreeNode a : preelement){
if(a.left!=null){
isFinish=true;
nowelement.add(a.left);
}
if(a.right!=null){
isFinish=true;
nowelement.add(a.right);
}
//全是空了
}
if(!isFinish)
break;
stack.push(nowelement);
preelement=nowelement;
}
while (!stack.empty()) {
List element=new ArrayList<>();
List nodes=stack.pop();
for(TreeNode aNode:nodes)
element.add(aNode.val);
result.add(element);
}
return result;
}
阅读(231) | 评论(0) | 转发(0) |