Java Implementation using stack and queue


  • 0
    S
    public class Solution {
        public List<List<Integer>> levelOrderBottom(TreeNode root) {
            LinkedList<List<Integer>> result = new LinkedList<List<Integer>>();
            Queue<TreeNode> nextLevel = new LinkedList<TreeNode>();
            
            if(root == null){
                return new LinkedList<List<Integer>>();
            }
    
            List<Integer> rootLevel = new LinkedList<Integer>();
            rootLevel.add(root.val);
            result.add(rootLevel);
            nextLevel.add(root);
            
            while(nextLevel.size() != 0){
                LinkedList<TreeNode> tempQueue = new LinkedList<TreeNode>();
                LinkedList<Integer> list = new LinkedList<Integer>();
                for(TreeNode node: nextLevel){
                    if(node.right != null){
                        tempQueue.add(node.right);
                        list.push(node.right.val);
                    }
                    if(node.left != null){
                        tempQueue.add(node.left);
                        list.push(node.left.val);
                    } 
                }
                if(list.size() != 0){
                    result.push(list);
                }
                nextLevel = tempQueue;
            }
            return result;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.