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

来源:互联网 发布:重装系统无法安装软件 编辑:程序博客网 时间:2024/06/06 19:58

题目:

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

程序:

层序遍历的应用

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