LeetCode-in-Java

1028. Recover a Tree From Preorder Traversal

Hard

We run a preorder depth-first search (DFS) on the root of a binary tree.

At each node in this traversal, we output D dashes (where D is the depth of this node), then we output the value of this node. If the depth of a node is D, the depth of its immediate child is D + 1. The depth of the root node is 0.

If a node has only one child, that child is guaranteed to be the left child.

Given the output traversal of this traversal, recover the tree and return its root.

Example 1:

Input: traversal = “1-2–3–4-5–6–7”

Output: [1,2,5,3,4,6,7]

Example 2:

Input: traversal = “1-2–3—4-5–6—7”

Output: [1,2,5,3,null,6,null,4,null,7]

Example 3:

Input: traversal = “1-401–349—90–88”

Output: [1,401,null,349,88,90]

Constraints:

Solution

import com_github_leetcode.TreeNode;

/*
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class Solution {
    private int ptr = 0;

    public TreeNode recoverFromPreorder(String traversal) {
        return find(traversal, 0);
    }

    private TreeNode find(String traversal, int level) {
        if (ptr == traversal.length()) {
            return null;
        }
        int i = ptr;
        int count = 0;
        while (traversal.charAt(i) == '-') {
            count++;
            i++;
        }
        if (count == level) {
            int start = i;
            while (i < traversal.length() && traversal.charAt(i) != '-') {
                i++;
            }
            int val = Integer.parseInt(traversal.substring(start, i));
            ptr = i;
            TreeNode root = new TreeNode(val);
            root.left = find(traversal, level + 1);
            root.right = find(traversal, level + 1);
            return root;
        } else {
            return null;
        }
    }
}