I'm struggling to solving No.1028 problem in LeetCode by myself. As a step of my solution, I wanna construct a binary tree below by adding nodes one by one in an order of 'preorder traversal'.
When I'm done with leftmost nodes with moving the cursor., now I'm supposed to add 'TreeNode(5)' as a right child node of 'TreeNode(2)'.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
root = TreeNode(1)
# cursor = root
# Add TreeNode(N) as a childNode
# cursor = cursor.left
# ...repeat
# Now cursor reaches TreeNode(4)
However, I have no idea of bactracking to the pre-visited nodes. I tried to do so by stacking pre-visited nodes in my stack and popping few times.
tmp = [TreeNode(1), TreeNode(2), TreeNode(3), TreeNode(4)]
tmp.pop()
tmp.pop()
cursor = tmp.pop()
But only to fail since cursor does contain TreeNode(2) but the tree-relationship between nodes are deleted (I know actually they are not deleted but just cursor becomes another class object).
Could anyone let me know how to visit parent node?
I tried to do so by stacking pre-visited nodes in my stack and popping few times.
That really is the way to do it.
tmp = [TreeNode(1), TreeNode(2), TreeNode(3), TreeNode(4)]
You should only create nodes as you process them from the input, and append them to the stack (using stack.append(node)
). Don't recreate nodes, as those will be different objects.
Before appending the node to the stack, you should first verify what the level is you get from the input. That should become the size of the stack -- so if the stack is larger than the level, then pop elements from it until the stack has the right size. Only then append the new node to the stack.
Finally, you need to establish the relationship between new node and its parent. Its parent is the preceding node on the stack. Remains to find out whether the new node should become a left child or a right child. If the parent happens to already have a left child, then make the new node the right child of the parent, otherwise it should become the left child.
With these ingredients you should be able to code it.
Here is a spoiler solution:
import re # Use regular expression to easily tokenise the input class Solution: def recoverFromPreorder(self, s): stack = [] for dashes, valstr in re.findall("(-*)(\d+)", s): level = len(dashes) node = TreeNode(int(valstr)) del stack[level:] # Potentially truncate the stack if level: # This node has a parent: establish link if not stack[-1].left: stack[-1].left = node else: stack[-1].right = node stack.append(node) return stack[0] # Test run root = Solution().recoverFromPreorder("1-2--3---4-5--6---7")