[leetcode]Populating Next Right Pointers in Each Node II

         1
       /  \
      2    3
     / \    \
    4   5    7


         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \    \
    4-> 5 -> 7 -> NULL


用O(1)的空间

那就利用next节点,一层一层的来遍历好了
首先是root,咱们把它的left和right连起来
而后root切换到下一层

而后遍历下一层的每一个节点(由于next连了的
再分别把他们的left,right什么的连起来

用两个变量就ok了
一个prev记录当前层前一节点是啥(用来链接的
一个next记录下一层的开始(用户切换到下一层

/**
 * 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) {
        TreeLinkNode* prev = nullptr;
        TreeLinkNode* next = nullptr;
        
        while(root) {
            prev = nullptr;
            next = nullptr;
            //if(next == nullptr) next = root->left ? root->left : root->right;
            for( ; root ; root = root->next) {
                if(next == nullptr) next = root->left ? root->left : root->right;
                if(root->left) {
                    if(prev) prev->next = root->left;
                    prev = root->left;
                }
                if(root->right) {
                    if(prev) prev->next = root->right;
                    prev = root->right;
                }
            }
            root = next;
        }
    }
};
 

注释的那一句,开始一位原本是同样的嘛,可是仔细一想,我第一个left多是空啊,当前层的第一个是叶子节点,可是他的兄弟不是啊spa

因此要写到循环里面,找到第一个有left或者right的节点,而后把left或者right(left优先)赋值给nextcode

相关文章
相关标签/搜索