A recursive solution in Java


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

Log in to reply
 

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