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

Code:

 1  void connect(TreeLinkNode *root) {

 2         if (!root)

 3             return ;

 4         deque<TreeLinkNode*>a;

 5         deque<TreeLinkNode*>b;

 6         a.push_back(root);

 7         

 8         while (!a.empty())

 9         {

10             while (!a.empty())

11             {

12                 TreeLinkNode* p = a.front();

13                 a.pop_front();

14                 if(p->left)

15                     b.push_back(p->left);

16                 if(p->right)

17                     b.push_back(p->right);

18                

19                if (a.empty())  

20                     p->next = NULL; 

21                else

22                     p->next = a.front();

23             }

24             a = b;

25             b.clear();

26         }

27     }

 

你可能感兴趣的:(right)