116. Populating Next Right Pointers in Each Node

1.問題

  • 將next指向右邊的node

2.想法

  • 提問

    • 確認題意: binary tree的類型, 若非perfect tree, 則無法確定left或right一定存在

  • function header, parameter

  • test input

  • 說明想法

  • 測試計算複雜度

3.程式碼

/**
 * 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);  
    }
};

Last updated