码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-04-15 19:24:46      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:for   基于   public   node   poi   pre   push   while   ext   

以下两种方法均适用于任意结构的树

方法一:使用栈的数据结构

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

标签:for   基于   public   node   poi   pre   push   while   ext   

原文地址:http://www.cnblogs.com/chengyuz/p/6715065.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!