Java O(n): Adding Nodes similar to LL


  • 0
    L
    public TreeNode addOneRow(TreeNode root, int v, int d) {
    	if (d == 1) {
    		TreeNode newRoot = new TreeNode(v);
    		newRoot.left = root;
    		return newRoot;
    	}
    	addNodeHelper(root, v, d);
    	return root;
    }
    
    private void addNodeHelper(TreeNode root, int v, int d) {
    	if (d == 2) {
    		TreeNode newNode = new TreeNode(v);
    		newNode.left = root.left;
    		root.left = newNode;
    
    		newNode = new TreeNode(v);
    		newNode.right = root.right;
    		root.right = newNode;
    	}
    
    	if (root.left != null) {
    		addNodeHelper(root.left, v, d - 1);
    	}
    	if (root.right != null) {
    		addNodeHelper(root.right, v, d - 1);
    	}
    }

Log in to reply
 

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