Different Straight Java Recursive Solution


  • 0
    M

    I kind of think fields are not supposed to be used unless necessary. So I came up with an idea that uses returned node to construct the tree.

    public void flatten(TreeNode root) {
    	help(root);
    }
    
    TreeNode help(TreeNode root) {
    
    	if (root == null)
    		return null;
    
    	if (root.left == null && root.right == null)
    		return root;
    
    	TreeNode right = root.right;
    	TreeNode left = root.left;
    	root.left = null;
    
    	if (left != null) {
    		root.right = left;
    		help(left).right = right;
    
    	}
    
    	return right != null ? help(right) : help(left);
    }

Log in to reply
 

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