Sunday, February 23, 2014

Leetcode: Populating Next Right Pointers in Each Node I&&II

Given a binary tree

struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *next;
    }

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Note:
  • You may only use constant extra space.
  • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example,
Given the following perfect binary tree,
         1
       /  \
      2    3
     / \  / \
    4  5  6  7
 After calling your function, the tree should look like:
        1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \  / \
    4->5->6->7 -> NULL
My Solution: This is a typical BFS problem. Instead of using the second queue to indicate a level, we can use the feature of a perfect binary tree: Number of nodes = 2^i - 1 (i = 1..n, ith level)
numNode indicates that current node is the nth in the original tree. If current node index is equal to 2^level - 1, current node is the rightmost node on the same level and its next is set to NULL. Otherwise its next is set to the first one in the queue.
Populating Next Right Pointers in Each Node II
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?
The equation  2^level - 1 doesn't hold any more.
Got a smart idea after doing google-search: use NULL as the indicator for the end of each level. Actually this method can also solve the first problem. Nice~~~~
My solution based on the idea:
Actually this problem can be solved in many different ways.



No comments:

Post a Comment