1. 程式人生 > >LetCode 117. 填充同一層的兄弟節點 II

LetCode 117. 填充同一層的兄弟節點 II

/**
 * 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:
//     void connect(TreeLinkNode *root) {
//         if (!root)
//            return;
//         TreeLinkNode* tmp = root->next;
//         // 找到下一個節點
//         while(tmp){
//             if (tmp->left){
//                 tmp = tmp->left;
//                 break;
//             }
//             if (tmp->right){
//                 tmp = tmp->right;
//                 break;
//             }
//             tmp = tmp->next;
//         }
//         // 注意先右後左,先把右邊的串起來,再串左邊
//         if (root->right) root->right->next = tmp;
//         if (root->left) root->left->next = root->right ? root->right : tmp;
//         connect(root->right);
//         connect(root->left);
//     }
// };
class Solution {
public:
    void connect(TreeLinkNode *root) {
        TreeLinkNode *start = new TreeLinkNode(0), *t = start;
        while(root){
            // 用start開頭的連結串列將這一層串起來
            if (root->left) {
                t->next = root->left;
                t = t->next;
            }
            if (root->right){
                t->next = root->right;
                t = t->next;
            }
            root = root->next;
            // 到達這層的盡頭了,進入下一層
            if (!root){
                root = start->next;
                start->next = NULL;
                t = start;
            }
        }
    }
};

static int x=[](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();