Leetcode 1028. Recover a Tree From Preorder Traversal

Input: traversal = "1-2--3--4-5--6--7"
Output: [1,2,5,3,4,6,7]
Input: traversal = "1-2--3---4-5--6---7"
Output: [1,2,5,3,null,6,null,4,null,7]
Input: traversal = "1-401--349---90--88"
Output: [1,401,null,349,88,90]
  • The number of nodes in the original tree is in the range [1, 1000].
  • 1 <= Node.val <= 109
  1. we will see dashes and value, so we verify it’s level and value while scan through the string
  2. because it’s in-order traversal, if the stack.size bigger than level, will pop out from the stack
  3. if the stack.peek().left is null, will add it into stack.peek().left; else add it into stack.peek().right
  4. to return the result, which is the root. We will need to pop all the other TreeNode in stack, until the last one -> the root
  5. Trick: use three variable in two for loops. Track index, level and value at the same time. Make sure index is not larger than string.length, to avoid overflow.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Gary Chiang

Gary Chiang

CS new grad, 6 years experience related to supply chain management. Located in Bay area