LeetCode --- Populating Next Right Pointers in Each Node II

题目链接

Problem 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

Accepted Code:
 1 /**
 2  * Definition for binary tree with next pointer.
 3  * struct TreeLinkNode {
 4  *  int val;
 5  *  TreeLinkNode *left, *right, *next;
 6  *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     void connect_helper(TreeLinkNode *root) {
12         if (root == NULL) return ;
13         //  when root is a leaf node
14         if (root->left == NULL && root->right == NULL) return;
15         if (root->left != NULL && root->right != NULL)
16             root->left->next = root->right;
17         
18         TreeLinkNode *p = NULL, *head = root; 
19         // iterator on the level
20         while (head->next != NULL && head->next->left == NULL && head->next->right == NULL)
21             head = head->next;
22         
23         if (head->next != NULL) {
24             if (head->next->left != NULL)
25                 p = head->next->left;
26             else
27                 p = head->next->right;
28         }
29         // right child is not null
30         if (root->right != NULL) 
31             root->right->next = p;
32         else 
33             root->left->next = p;
34         // recursive solve right and left child of root
35         // attention that the right child should be proceeded first
36         connect_helper(root->right);
37         connect_helper(root->left);
38     }
39     void connect(TreeLinkNode *root) {
40         // root = NULL
41         if (root == NULL) return ;
42         // deal root node
43         root->next = NULL;
44          
45         connect_helper(root);
46     } 
47 };




原文地址:https://www.cnblogs.com/Stomach-ache/p/3779987.html