Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public List<List<Integer>> levelOrder(TreeNode root) {
- Stack<TreeNode> s1 = new Stack<>();
- Stack<TreeNode> s2 = new Stack<>();
- s1.add(root);
- List<List<Integer>> res = new ArrayList<>();
- if(root == null)
- return res;
- List<Integer> level = new ArrayList<>();
- while(!s1.isEmpty() || !s2.isEmpty()){
- level = new ArrayList<>();
- while(!s1.isEmpty()){
- TreeNode temp = s1.pop();
- level.add(temp.val);
- if(temp.left != null)
- s2.push(temp.left);
- if(temp.right != null)
- s2.push(temp.right);
- }
- res.add(level);
- // reversing the elemenst in stack s1 by putting them in s2
- while(!s2.empty())
- {
- TreeNode temp = s2.pop();
- s1.push(temp);
- }
- }
- return res;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement