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

/**
 * 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 == NULL)
//            return;
//         // 左兒子的next等於right,右兒子的next:如果他的父節點的next不爲空,右兒子的next等於父節點的next節點的左兒子,否則爲空
//         if (root->left) 
//             root->left->next = root->right,root->right->next = root->next != NULL ? root->next->left : NULL;
//         connect(root->left);
//         connect(root->right);
//     }
// };
class Solution {
public:
    void connect(TreeLinkNode *root) {
        if (root == NULL)
           return;
        root->next = NULL;
        TreeLinkNode *start = root, *cur;
        // 用start記錄每層的開始節點,然後一層一層遍歷
        while(start->left != NULL){
            cur = start;
            while(cur != NULL) cur->left->next = cur->right, cur->right->next = cur->next != NULL ? cur->next->left : NULL, cur = cur->next;
            start = start->left;
        }
    }
};

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章