https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/#/description
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
- You may only use constant extra space.
For example,
Given the following binary tree,
1 / 2 3 / 4 5 7
After calling your function, the tree should look like:
1 -> NULL / 2 -> 3 -> NULL / 4-> 5 -> 7 -> NULL
# Definition for binary tree with next pointer. # class TreeLinkNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None class Solution: # @param root, a tree link node # @return nothing def connect(self, root): # recursion # it can solve Populating Next Right Pointers in Each Node I. # To handle the right sub node, the first thought pops out is BFS. However, BFS does not take up constant space # Time O(n) Space(1) if not root: return # dummy stores node on the previous level. dummy = TreeLinkNode(0) curr = root prev = dummy while curr: if curr.left: prev.next = curr.left prev = prev.next if curr.right: prev.next = curr.right prev = prev.next curr = curr.next self.connect(dummy.next)
Note:
1 Use built in class given by the question.
Get the first element of a tree using class TreeLinkNode.
dummy = TreeLinkNode(0)
Sol 2:
Iteration.
Not very different from the recursion method. Just change the way we forward the dummy variable.
"
The algorithm is a BFS or level order traversal. We go through the tree level by level. node is the pointer in the parent level, tail is the tail pointer in the child level.
The parent level can be view as a singly linked list or queue, which we can traversal easily with a pointer.
Connect the tail with every one of the possible nodes in child level, update it only if the connected node is not nil.
Do this one level by one level. The whole thing is quite straightforward.
"
# Definition for binary tree with next pointer. # class TreeLinkNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None class Solution: # @param root, a tree link node # @return nothing def connect(self, node): # iteration tail = dummy = TreeLinkNode(0) while node: tail.next = node.left if tail.next: tail = tail.next tail.next = node.right if tail.next: tail = tail.next node = node.next if not node: tail = dummy node = dummy.next