Clean JAVA 1ms Recursive Solution


  • 0
    T
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public void flatten(TreeNode root) {
            if(root==null){
                return;
            }
            flatten(root.left);
            flatten(root.right);
            
            //add right to left's bottom-most right
            //move left to right
            //make left null
            TreeNode ptr = root.left;
            if(ptr!=null){
                while(ptr.right!=null){
                    ptr = ptr.right;
                }
                ptr.right = root.right;
                root.right = root.left;
                root.left = null;
            }
            
        }
    }

Log in to reply
 

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