O(n) Time + O(n) Space Iterative

  • 0

    I use the serialize method from other's post.
    The deserialize method use a stack to trace the current largest values.
    I just initiate a root and push it into the stack(st).
    For each value v: if v < st.peek()
    that means this value is the left child of the stack's peek.
    if the v > st.peek(), that means the value can be peek's right child or one of peek's parents' right child. We just pop the stack to find the right node.
    I use a special case to handle the root.

        // Encodes a tree to a single string.
        public String serialize(TreeNode root) {
            if(root == null) return null;
            String left = serialize(root.left);
            String right = serialize(root.right);
            if(left == null && right == null) return root.val+"";
            StringBuilder sb = new StringBuilder();
            if(left != null) sb.append(","+left);
            if(right != null) sb.append(","+right);
            return sb.toString();
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            if (data == null || data.length() == 0) return null;
            String []vals = data.split(",");
            Stack<TreeNode> st = new Stack<>();
            TreeNode root = new TreeNode(Integer.parseInt(vals[0]));
            for (int i = 1; i < vals.length; i++) {
                int peekVal = st.peek().val;
                int cur = Integer.parseInt(vals[i]);
                if (cur < peekVal) {
                    TreeNode l = new TreeNode(cur);
                    st.peek().left = l;
                else {
                    TreeNode last = null, next = null;
                    do {
                        last = st.pop();
                        if (st.isEmpty()) next = null;
                        else next = st.peek();
                    }while (!st.isEmpty() && next.val < cur);
                    if (next == null) {
                        last.right = new TreeNode(cur);
                    else {
                        last.right = new TreeNode(cur);
            return root;

Log in to reply

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