leetcode:Populating Next Right Pointers in Each Node

本文介绍了一个解决方案,用于填充二叉树中每个节点的next指针,使其指向同一层级的下一个节点。通过迭代的方式遍历二叉树的每一层,将每一层的左右子节点的next指针连接起来。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


/**
 * https://leetcode.com/problems/populating-next-right-pointers-in-each-node/#/description
 *
 */


#include<iostream>
#include<vector>
#include<stack>
using namespace std;
using vecIter = std::vector<int>::iterator;


struct TreeLinkNode { 
    int val;
    TreeLinkNode *left, *right, *next;
    TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
};


class Solution
{
public:
     Solution(){};
    ~ Solution(){};
    void connect(TreeLinkNode* root){

        if(NULL==root) return;
        TreeLinkNode* curLev;
        while(root->left!=NULL){
            curLev=root;
            while(curLev!=NULL){
                curLev->left->next=curLev->right;
                if(curLev->next!=NULL)
                    curLev->right->next=curLev->next->left;
                curLev=curLev->next;
            }
            root=root->left;
        }
    }

};

// Test Unit
//
//          1
//         / \
//        2   3
//       /\   /\
//      4 5  6  7
//     /\ /\ /\ /\
//    8 9A BC DE F
// ( A == 10 ...)

TreeLinkNode* createBinaryTree(vecIter beg,vecIter end)
{
    vector<TreeLinkNode*> vec;

    //把vector数组的int型内容,转化为树结构类型,存到vec数组当中
    for(vecIter it=beg;it!=end;++it)            
        vec.push_back(new TreeLinkNode(*it));

    //把vec数组中的结果组织成树的形式
    for(int i=0,pos=0;pos!=vec.size()-1;++i)
    {
        vec[i]->left=vec[++pos];
        vec[i]->right=vec[++pos];
    }

    //返回起始地址
    return *vec.begin();
}

//输出节点的内容
void print(TreeLinkNode* root)
{
    while(root)
    {
        cout<<root->val;
        TreeLinkNode* cur=root->next;
        while(cur)
        {
            cout<<"->"<<cur->val;
            cur=cur->next;
        }
        cout<<endl;
        root=root->left;
    }
}

int main(int argc,char** argv){
    vector<int> vec={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
    TreeLinkNode* root=createBinaryTree(vec.begin(),vec.end());

    Solution s;
    s.connect(root);
    print(root);

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值