java solution, easy to understand


  • 0
    Q
    public class Solution {
         public void flatten(TreeNode root) {
            if(root == null) return;
            build(root,root.left,root.right);
         }
    private void build(TreeNode head,TreeNode mid, TreeNode last) {
        flatten(last);
        if(head == null || mid == null) return;
        head.right = mid; 
        head.left = null;
        TreeNode tail = mid;
        build(mid,mid.left,mid.right);
        while (tail.right !=null) tail = tail.right; // find the last node
        tail.right = last;
    }
    

    }


Log in to reply
 

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