Java Preorder 1ms Solution


  • 2
    M
    public class Solution {
        TreeNode current;
        public void flatten(TreeNode root) {
            //if we've been given a null root, just return
            if(root == null){ return; }
            flattenTree(root);
            
        }
        
        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; }
            else
            {
                //add current TreeNode to the end of the list
                current.right = root;
                current = current.right;
            }
            
            //DFS, so go left and then right
            flattenTree(left);
            flattenTree(right);
        }
    }

Log in to reply
 

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