Populating next right pointers in each node II

Source: Internet
Author: User

Follow up for problem"Populating next right pointers in each node".

What if the given tree cocould be any binary tree? Wocould 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 shoshould look like:

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

Click to open the original question link

Basically, you can modify the layer traversal slightly. The algorithm is relatively simple. Pay attention to the bottom boundary conditions. You can also put each layer in the vector <>, but new memory will be opened up.

Directly determine whether the code is on the first layer. The code is a little more complicated.

struct TreeLinkNode  {  int val;  TreeLinkNode *left, *right, *next;  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}}; struct node { int level; TreeLinkNode* TLN; };class Solution {public:void connect(TreeLinkNode *root) {if (root == NULL){return;}deque<node> deque_TreeLinkNode;node pre,current;pre.level = 0;pre.TLN = root;deque_TreeLinkNode.push_back(pre);pre.TLN = NULL;while(!deque_TreeLinkNode.empty()){node temp = deque_TreeLinkNode.front();if (temp.TLN->left != NULL){node left;left.level = temp.level+1;left.TLN = temp.TLN->left;deque_TreeLinkNode.push_back(left);}if (temp.TLN->right != NULL){node right;right.level = temp.level+1;right.TLN = temp.TLN->right;deque_TreeLinkNode.push_back(right);}current= deque_TreeLinkNode.front();deque_TreeLinkNode.pop_front();if (pre.TLN == NULL){pre.TLN = current.TLN;pre.level = current.level;//deque_TreeLinkNode.pop_front();continue;}else{if (current.level == pre.level){pre.TLN->next = current.TLN;pre=current;continue;//current->TLN = NULL;//current->level = 0;}else{pre.TLN->next = NULL;pre = current;}}}pre.TLN->next = NULL;}private:};





Populating next right pointers in each node II

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.