Easy 1ms Java DFS solution


  • 1
    Y

    remember to set root.left = null; otherwise you get runtime error!

    ===

    public class Solution {
    public void flatten(TreeNode root) {
    // 10:28am - 10:47am
    flattenHelper(root);
    }

    private TreeNode flattenHelper(TreeNode root) {
    	// return the far right "tail" node of the flattened tree
    	// TODO: one not null
    	if (root == null || root.left == null && root.right == null) {
    		return root;
    	}
    	if (root.left == null) {
    		return flattenHelper(root.right);
    	}
    	if (root.right == null) {
    		root.right = root.left;
    		root.left = null;
    		return flattenHelper(root.right);
    	}
    	// left != null && right != null
    	TreeNode leftTail = flattenHelper(root.left);
    	TreeNode rightTail = flattenHelper(root.right);
    	leftTail.right = root.right;
    	root.right = root.left;
    	root.left = null;
    	return rightTail;
    }
    

    }


Log in to reply
 

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