Populating Next Right Pointers in Each Node(I,II)

Posted xpp

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Populating Next Right Pointers in Each Node(I,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;
        
        stack<TreeLinkNode *> s;
        s.push(root);
        while(!s.empty())
        {
            vector<TreeLinkNode *>tmp;
            TreeLinkNode *prev = s.top();
            tmp.push_back(s.top());
            s.pop();
            
            while(!s.empty())
            {
                TreeLinkNode *cur = s.top();
                tmp.push_back(s.top());
                s.pop();
                prev->next = cur;
                prev = cur;
            }
            
            for(int i=tmp.size()-1; i >= 0; --i)
            {
                if(tmp[i]->right)
                    s.push(tmp[i]->right);
                if(tmp[i]->left)
                    s.push(tmp[i]->left);
            }
        }
    }
};

方法二:基于层次遍历的方法,使用指针记录下一层首先遍历的节点

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

 

以上是关于Populating Next Right Pointers in Each Node(I,II)的主要内容,如果未能解决你的问题,请参考以下文章

树Populating Next Right Pointers in Each Node

116. Populating Next Right Pointers in Each Node

116. Populating Next Right Pointers in Each Node

116. Populating Next Right Pointers in Each Node

116. Populating Next Right Pointers in Each Node

116. Populating Next Right Pointers in Each Node