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?