117. Populating Next Right Pointers in Each Node II

Follow up for problem "Populating Next Right Pointers in Each Node".spa

What if the given tree could be any binary tree? Would your previous solution still work?指针

Note:code

  • You may only use constant extra space.

 

For example,
Given the following binary tree,blog

         1
       /  \
      2    3
     / \    \
    4   5    7

 

After calling your function, the tree should look like:io

         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \    \
    4-> 5 -> 7 -> NULL
本题的解法和116题不一样,116题也能够用本题的解法,思路都很简单。首先,对这个二叉树进行层次遍历,放入一个节点指针的vector<vector<TreeLinkNode*>>中,而后再将这个vector中元素进行next指针赋值。
代码:
 1 void mid_next(TreeLinkNode* root,int dep)
 2 {
 3     if (root==NULL)
 4         return;
 5     if (level.size()>dep)
 6         level[dep].push_back(root);
 7     else
 8     {
 9         vector<TreeLinkNode*> onelevel;
10         onelevel.push_back(root);
11         level.push_back(onelevel);
12     }
13     int deps=dep+1;
14     mid_next(root->left,deps);
15     mid_next(root->right,deps);
16 }
17 
18 void add_next()
19 {
20     for (int i=0;i<level.size();i++)
21     {
22         int size=level[i].size();
23         if (size==1)
24             level[i][0]->next=NULL;
25         else
26         {
27             for (int j=1;j<size;j++)
28             {
29                 level[i][j-1]->next=level[i][j];
30             }
31             level[i][size-1]->next=NULL;
32         }
33     }
34 }
35 
36 void connect(TreeLinkNode *root)
37 {
38     if(root==NULL)
39         return;
40     mid_next(root,0);
41     add_next();        
42 }
相关文章
相关标签/搜索