LeetCode 107: The level traversal of binary tree II(java)
subject :
answer :
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<List<Integer>> res=new ArrayList<>();
Stack<List<Integer>> stack=new Stack<>();
public List<List<Integer>> levelOrderBottom(TreeNode root) {
if(root==null)
return res;
TreeNode nodeTemp=root;
Queue<TreeNode> nodeQueue=new LinkedList<>();
nodeQueue.add(nodeTemp);
while(!nodeQueue.isEmpty()){
int length=nodeQueue.size();
List<Integer> list =new ArrayList<>();
for(int i=0;i<length;i++){
nodeTemp=nodeQueue.poll();
list.add(nodeTemp.val);
if(nodeTemp.left!=null)
nodeQueue.add(nodeTemp.left);
if(nodeTemp.right!=null)
nodeQueue.add(nodeTemp.right);
}
stack.push(list);
}
while(!stack.isEmpty()){
res.add(stack.pop());
}
return res;
}
}