首页 > 代码库 > 【LeetCode】Populating Next Right Pointers in Each Node II

【LeetCode】Populating Next Right Pointers in Each Node II

Populating Next Right Pointers in Each Node II

Follow up for problem "Populating Next Right Pointers in Each Node".

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

  • You may only use constant extra space.

 

For example,
Given the following binary tree,

         1       /        2    3     / \        4   5    7

 

After calling your function, the tree should look like:

         1 -> NULL       /        2 -> 3 -> NULL     / \        4-> 5 -> 7 -> NULL

 

先使用队列进行BFS(O(n)),队列中的节点还需要存放当前所在层数。

如果前一个遍历到的节点pre与当前遍历到的节点cur不在同一层,那么pre->next需要指向NULL

如果在同一层,那么pre->next = cur

/** * 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) {} * }; */struct Node{    TreeLinkNode* tree;    int level;    Node(TreeLinkNode* root, int l):tree(root),level(l) {}};class Solution {public:    queue<Node*> q;    void connect(TreeLinkNode *root)     {        if(root == NULL)            return;        Node* rootNode = new Node(root, 0);        q.push(rootNode);        Node *cur = rootNode;        Node *pre = rootNode;        Node *temp = rootNode;        while(!q.empty())        {            temp = q.front();            q.pop();            if(temp->tree->left)            {                Node* leftNode = new Node(temp->tree->left, temp->level+1);                q.push(leftNode);                pre = cur;                cur = leftNode;                if(pre->level < cur->level)                //get to next level                    pre->tree->next = NULL;                else                //still same level                    pre->tree->next = cur->tree;            }            if(temp->tree->right)            {                Node* rightNode = new Node(temp->tree->right, temp->level+1);                q.push(rightNode);                pre = cur;                cur = rightNode;                if(pre->level < cur->level)                //get to next level                    pre->tree->next = NULL;                else                //still same level                    pre->tree->next = cur->tree;            }        }    }};

【LeetCode】Populating Next Right Pointers in Each Node II