JAVA code - Can someone tell me why I get Wrong answer with input {1,2}


  • 0
    Y

    I got the result {1,2} with input {1,2}. The expected answer is {1, #, 2}.Where is wrong with my code?

    My idea was: 1). turn the tree into a String in the pre-order way. then 2) build every TreeNode with the numbers got from the String. Set every next node to the right of the previous node.

    public class Solution {
    public void flatten(TreeNode root) {
        
        if (root==null || (root.left==null && root.right==null)){}
        else{
            
            String nums = getString(root);
            Scanner s=new Scanner(nums);
            
            root=new TreeNode(Integer.parseInt(s.next()));
            root.left=null;
            //root.right=null;
            TreeNode p=root;
             
            
            while (s.hasNext()){
                TreeNode temp=new TreeNode(Integer.parseInt(s.next()));
                temp.left=null;
               // temp.right=null;
                p.right=temp;
                p=p.right;
            }
            
        }
        
        
    }
    
    public String getString(TreeNode root){
        
        if (root==null) return "";
        if (root.left==null && root.right==null) return Integer.toString(root.val);
        
        return Integer.toString(root.val)+"  "+getString(root.left)+"  "+getString(root.right);
        
    }
    

    }


Log in to reply
 

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