What is wrong with this JAVA code? Time exceeded! why??


  • -2
    S
    Stack<TreeNode> sta = new Stack<TreeNode>();
            List<List<Integer>> fin = new LinkedList<List<Integer>>();
            List<Integer> subList = new LinkedList<Integer>();
            if(root == null)
                return fin;
            sta.push(root);
            while(!sta.isEmpty()) {
                int size = sta.size();
                for(int i = 0; i < size; i++) {
                    if(sta.peek().left != null) 
                        sta.push(sta.peek().left);
                    if(sta.peek().right != null) 
                        sta.push(sta.peek().right);
                }
            }
            while(!sta.isEmpty()) {
                TreeNode node = sta.pop();
                subList.add(sta.pop().val);
                subList.add(node.val);
            }
            fin.add(subList);
            return fin;
    

    what's wrong with this code version? I can't figure it out, Please help!


  • 0
    L

    while(!sta.isEmpty()) {
    int size = sta.size();
    for(int i = 0; i < size; i++) {
    if(sta.peek().left != null)
    sta.push(sta.peek().left);
    if(sta.peek().right != null)
    sta.push(sta.peek().right);
    }
    }
    will run forever. The size of sta never get reduced.


  • 0
    E

    public List<List<Integer>> levelOrderBottom(TreeNode root) {
    TreeNode cur;
    List<List<Integer>> list=new LinkedList<List<Integer>>();
    Queue<TreeNode> queue=new LinkedList<TreeNode>();
    Stack<List<Integer>> stack=new Stack<List<Integer>>();

            if(root==null)
            return list;
            
            cur=root;
            queue.offer(cur);
            while(!queue.isEmpty())
            {
                List<Integer> listline=new LinkedList<Integer>();
                int size=queue.size();
                for(int i=0;i<size;i++)
                {
                    TreeNode tmp=queue.poll();
                    listline.add(tmp.val);
                    if(tmp.left!=null)
                    {
                        queue.offer(tmp.left);
                    }
                    if(tmp.right!=null)
                    {
                        queue.offer(tmp.right);
                    }
                }
                stack.push(listline);
            }
            while(!stack.isEmpty())
            {
                list.add(stack.peek());
                stack.pop();
            }
            return list;
        }

Log in to reply
 

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