Recursive Java solution


  • 0
    public class Solution {
        public void flatten(TreeNode root) {
            if (root == null || (root.left == null && root.right == null)) return;
            
            if (root.left != null) {
                addToRight(root.right, root.left);
                root.right = root.left;
                root.left = null;
            }
            
            flatten(root.right);
        }
        
        private void addToRight(TreeNode node, TreeNode head) {
            if (head.right == null) {
                head.right = node;
                return;
            }
            
            addToRight(node, head.right);
        }
    }
    

Log in to reply
 

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