Don't know what's wrong with my java solution using queue


  • -1
    B

    /**

    • Definition for binary tree

    • public class TreeNode {

    • int val;
      
    • TreeNode left;
      
    • TreeNode right;
      
    • TreeNode(int x) { val = x; }
      
    • }
      */
      public class Solution {
      public List<List<Integer>> levelOrder(TreeNode root) {
      Queue<TreeNode> q = new PriorityQueue<TreeNode>();
      List<Integer> list = new ArrayList<Integer>();
      List<List<Integer>> lists = new ArrayList<List<Integer>>();

       if(root != null)
           q.add(root);
       
       while(! q.isEmpty()){
           TreeNode x = q.remove();
           list.add(x.val);
           
           if(root.left != null){
               q.add(root.left);
           }
           if(root.right != null){
               q.add(root.right);
           }
           
       }
       
       lists.add(list);
       return lists;
      

      }
      }

    It says runtime error, and the last input is {1, 2}.


  • 0
    A
    if(root.left != null){
                q.add(root.left);
            }
            if(root.right != null){
                q.add(root.right);
            }
    
    
    ---> replace with 
    
    if(x.left != null){
                q.add(x.left);
            }
            if(x.right != null){
                q.add(x.right);
            }
    

    You are trying to add root.left and root.right everytime and it will go into an infinite loop


Log in to reply
 

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