An in-order version in Java


  • 0
    X
    public static class Range {
        TreeNode head;
        TreeNode tail;
        public Range(TreeNode head, TreeNode tail) {
            this.head = head;
            this.tail = tail;
        }
    }
    
    /**
     * @param root of the tree
     * @return a range represents head and tail of flatten list { head, tail 
     */
    public Range flattenInorder(TreeNode root) {
        Range ans = new Range(root, root);
        if (root.left != null) {
            Range left = flattenInorder(root.left);
            ans.head = left.head;
            left.tail.right = root;
        }
        if (root.right != null) {
            Range right = flattenInorder(root.right);
            ans.tail = right.tail;
            root.right = right.head;
        }
        root.left = null;
        return ans;
    }

Log in to reply
 

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