Java Solution using Level Order Traversal


  • 0
    T
    List<List<Integer>> result = new ArrayList<>();
            if(root == null)
                return result;
            Queue<TreeNode> queue = new LinkedList<>();
            queue.add(root);
            boolean flag = true;
            while(!queue.isEmpty()) {
                int size = queue.size();
                List<Integer> lst = new ArrayList<>();
                Stack<Integer> stack = new Stack<>();
                for(int i = 0; i < size; i++) {
                    TreeNode currNode = (TreeNode) queue.remove();
                    if(flag) {
                        if(i == size-1)
                            flag = false;
                        lst.add(currNode.val);
                    } else {
                        if(i == size-1)
                            flag = true;
                        stack.push(currNode.val);
                    }
                    if(currNode.left != null) queue.add(currNode.left);
                    if(currNode.right != null) queue.add(currNode.right);
                }
                while(!stack.isEmpty()) {
                    lst.add(stack.pop());
                }
                result.add(lst);
            }
            return result;
    

Log in to reply
 

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