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 }
相關文章
相關標籤/搜索