Is the object generated in the function disappear after the call? Even if I use a pointer as a tracker?


  • 0
    H
    public class Solution {
    public void flatten(TreeNode root) {
        if(root == null || root.left == null && root.right == null) {
            return;
        }
        TreeNode newRoot = null;
        subProblem(root, newRoot);
        root = newRoot;
    }
    
    public TreeNode subProblem(TreeNode root, TreeNode currentNode) {
        if(root != null) {
            currentNode = root;
            currentNode.left = null;
            currentNode = currentNode.right;
            currentNode = subProblem(root.left, currentNode);
            currentNode = subProblem(root.right, currentNode);
        }
        return currentNode;
    }
    }
    

    This code doesn't work...

    What I am curious about is when I use a ArrayList as a parameter, I can add stuff in this ArrayList. But is there any difference between these codes? Since in my opinion, arrayList is also a pointer parameter.

    After that, I come up with another solution, but it only works in my ellipse with input [1,2]. Which my result is a node with value 1 with a right child with value 2. however, it says my code is giving [1,2] as a result. Can anyone tell what's wrong with my code?

    public class Solution {
    public void flatten(TreeNode root) {
        if(root == null || root.left == null && root.right == null) {
            return;
        }
        ArrayList<Integer> list = new ArrayList<Integer>();
        subProblem(root, list);
        
        if(list.size() != 0) {
            root = new TreeNode(list.get(0));
            TreeNode currentNode = root;
            for(int i = 1; i < list.size(); i++) {
                currentNode.right = new TreeNode(list.get(i));
                currentNode = currentNode.right;
            }
        }
    }
    
    public void subProblem(TreeNode root, ArrayList<Integer> list) {
        if(root != null) {
            list.add(root.val);
            subProblem(root.left, list);
            subProblem(root.right, list);
        }
    }
    }

Log in to reply
 

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