Java Preorder 1ms Solution

  • 2
    public class Solution {
        TreeNode current;
        public void flatten(TreeNode root) {
            //if we've been given a null root, just return
            if(root == null){ return; }
        private void flattenTree(TreeNode root)
            if(root == null){ return; }
            //set local variables for left and right
            TreeNode left = root.left, right = root.right;
            //set root.left and root.right to null since we don't want to add them to our resulting linked list
            root.left = null;
            root.right = null;
            //if it's the first run of this function set current to root (the start of the linked list)
            if( current == null ){ current = root; }
                //add current TreeNode to the end of the list
                current.right = root;
                current = current.right;
            //DFS, so go left and then right

Log in to reply

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