Leetcode在线编程populating-next-right-pointers-in-each-node

来源:互联网 发布:山东大学网络教育首页 编辑:程序博客网 时间:2024/05/17 04:30

Leetcode在线编程 populating-next-right-pointers-in-each-node

题目链接

populating-next-right-pointers-in-each-node

题目描述

Given a binary tree
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set toNULL.
Initially, all next pointers are set toNULL.
Note:
You may only use constant extra space.
You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

For example,
Given the following perfect binary tree,
1
/ \
2 3
/ \ / \
4 5 6 7

After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ / \
4->5->6->7 -> NULL


题意

简单点就是,给定完全二叉树,将它每一层的顶点串起来

解题思路

我采用的是非递归去层次遍历完全二叉树
设置一个队列q保存当前层的顶点
设置一个动态数组v保存下一层的顶点
具体操作:
队列q中pop出结点tmp
1)就将tmp的左右节点,保存在v中,等待下次遍历,这样就可以保证队列q是同一层的顶点
2)tmp接到链表尾部pre->next,同时将pre =tmp ,就将同一层的顶点串起来了

AC代码

class Solution {public:    void connect(TreeLinkNode *root) {        if(root==NULL)            return ;        queue<TreeLinkNode*>q;        q.push(root);        while(!q.empty())        {            TreeLinkNode* pre =NULL;            vector<TreeLinkNode*>v;            while(!q.empty())            {                TreeLinkNode *tmp1 = q.front();                q.pop();                if(pre==NULL)                {                    tmp1->next  = NULL;                    pre = tmp1;                }                else                {                     pre ->next = tmp1;                    pre = tmp1;                    pre->next =NULL;                }                if(tmp1->left)                    v.push_back(tmp1->left);                if(tmp1->right)                    v.push_back(tmp1->right);            }            for(int i = 0 ; i < v.size() ; i++)            {                q.push(v[i]);                }        }    }};
0 0
原创粉丝点击