Could someone help me out, not sure what I did wrong here(JAVA)


  • 0
    W

    Hi everyone, I am trying to solve this by recursion for now but cannot figure out what's wrong with my logic or code. My idea is I pass a node (root) to the helper function that it will assign node's original left child to its right , and find the rightest child in the node's left subtree, which s right child will be assigned with node's right original right child. My code pass 97 cases but get wrong answer at test case [1,2,null,3], which looks ok if I run it on my own IDE,,,,I know this is not a good solution,,but please correct me if I am making some wrong assumption. Thanks!

    public void flatten(TreeNode root) {
    	if(root == null) return;
    	helper(root);	
    }
    public TreeNode helper(TreeNode node){
    	if(node == null){
    		return null;
    	}
    	if(node.left == null && (node.right == null)){
    	    return node;
    	}
    		
    	TreeNode oldRight = node.right;
    	TreeNode oldLeft = node.left;
    	TreeNode leftSubRightest = null; //rightest node in left subtree for assigning oldRight's parent
    		
    	if(node.left == null){
    		node.right = oldRight;
    	}else{
    		node.right = oldLeft;
    		leftSubRightest = helper(oldLeft);
    		leftSubRightest.right = oldRight;
    		node.left = null;
    	}
    	TreeNode rightestIncludingNode = helper(oldRight);
    	return rightestIncludingNode == null ? node : rightestIncludingNode;
    }
    	
    

Log in to reply
 

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