Accepted Java Solution


  • 0
    F

    class Solution {

    public void flatten(TreeNode root) {
        preorder(root);
    }
    public TreeNode preorder(TreeNode curr) {
        if (curr != null) {
            if (curr.right == null && curr.left == null) {
                return curr;
            } else {
                TreeNode left = preorder(curr.left);
                TreeNode right = preorder(curr.right);
                if (left != null) {
                    TreeNode head = left;
                    TreeNode tail = head;
                    while (tail.right != null) {
                        tail = tail.right;
                    }
                    curr.right = head;
                    tail.right = right;
                    curr.left = null;
                }
                return curr;
            }
        }
        return null;
    }
    

    }


Log in to reply
 

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