# 116. Populating Next Right Pointers in Each Node

## 1.問題&#x20;

* 將next指向右邊的node

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LNL17k7UO9Z0MeZenA3%2F-LNL3DzbYeFjvpar1Lrb%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-09-26%20%E4%B8%8B%E5%8D%889.26.20.png?alt=media\&token=493d0743-236b-4375-aba9-ba765936ae81)

## 2.想法 <a href="#id-2-xiang-fa" id="id-2-xiang-fa"></a>

* 提問
  * 確認題意:  binary tree的類型, 若非perfect tree, 則無法確定left或right一定存在
* function header, parameter
* test input
* 說明想法
* 測試計算複雜度

## **3.程式碼** <a href="#id-3-cheng-shi" id="id-3-cheng-shi"></a>

```
/**
 * Definition for binary tree with next pointer.
 * struct TreeLinkNode {
 *  int val;
 *  TreeLinkNode *left, *right, *next;
 *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 * };
 */
class Solution {
public:
    Node* connect(Node* root) {
        pointNext(root);
        return root;
    }
private:
    void pointNext(Node *root) {
        if (!root) {
            return;
        }
        if (root->left) {
           root->left->next = root->right;
        } 
        if (root->right && root->next) {
            root->right->next = root->next->left;
        } 
        pointNext(root->left);
        pointNext(root->right);  
    }
};
```
