Leetcode Populating Next Right Pointers in Each Node II

OpenSoucre發表於2014-07-02

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

 題目看起來比較複雜,如果把它當做對二維陣列建立連結串列,此時就容易想了

主要難點就是有上一層如何去控制下一層,你可以根據連結串列的思路,用一個dummy結點,每次指向新的一行,然後根據按照連結串列遍歷思路,根據next結點去遍歷,一邊遍歷一邊新增下一層的結點。

class Solution {
public:
    void connect(TreeLinkNode *root) {
        if(root == NULL) return;
        root->next =NULL;
        TreeLinkNode *start = root, *nextStart = new TreeLinkNode(0),*p = nextStart;
        while(start){
            if(start->left) {p->next = start->left;p = p->next;}
            if(start->right){p->next = start->right;p = p->next;}
            if(start->next ==NULL ){
                p->next = NULL;
                start = nextStart->next;
                p = nextStart;
            }else start = start->next;
        }
    }
};

 

 

相關文章