Leetcode_Populating Next Right Pointers in Each Node II

来源:互联网 发布:淘宝天猫入驻 编辑:程序博客网 时间:2024/05/17 12:23

Question link: http://oj.leetcode.com/problems/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?

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

Solution:

According to my thought first:

For each node, root. if all nodes that's one level above root is already connected, we can find next for root by iterating all nodes that is one level above the current node. First, I subconsciously adhere to the convention of dealing with the left child first, then the right child. that's what i just do it. One problem occurs. For a tree deep enough, not all the nodes one level above the current node is connected. Cause, the right part of the whole tree is not yet dealt with.

I thought about it for some time. Still can't come up a new idea. One simple idea is to repeat what's initial proposed several times until no 'next' field is updated.

I have to Google the answer, now.

And the answer is deal with the right tree first...

Hint:

Some times you have to beat your subconsciousness to gain a new solution.

How to beat your subconsciousness? Know your subconsciousness first. (That's another story i have learned from learning physics in high school.)

From: http://blog.csdn.net/cheetach119/article/details/12289867