Divide and conquer recursive solution. 1ms


  • 0
    R
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        class Node {
            TreeNode head;
            TreeNode tail;
            public Node(TreeNode h, TreeNode t) {
                this.head = h;
                this.tail = t;
            }
        }
        public void flatten(TreeNode root) {
            if (root == null) {
                return;
            } else {
                helper(root);
            }
        }
        
        Node helper(TreeNode node) {
            if (node == null) {
                return null;
            }
            Node left = helper(node.left);
            Node right = helper(node.right);
            node.left = null;
            Node cur = new Node(node, node);
            if (left == null && right == null) {
                return cur;
            }
            if (left != null) {
                node.right = left.head;
                cur.tail = left.tail;
            }
            if (right != null) {
                cur.tail.right = right.head;
                cur.tail = right.tail;
            }
            return cur;
        }
    }
    

Log in to reply
 

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