Topic:
Given a binary tree
struct Treelinknode { treelinknode *left; Treelinknode *right; Treelinknode *next; }
populate Each of the next pointer to the next right node. If There is no next right node, the next pointer should be set To
initially, all next pointers is set To
note:
- you may only use constant extra space.
- You May assume that it's a perfect binary tree (ie, all leaves be at the same level, and every parent have both children).
For example,
Given the following perfect binary tree,
1 / 2 3 /\ / 4 5 6 7
After calling your function, the tree is should look like:
1, NULL / 2, 3, null /\ / 4->5->6->7, NULL
Idea: Just add each node to a next node, for a tree, the next node is assigned, and is a complete binary tree, you can use the hierarchical traversal, for each layer is modified.
void Connect (bintree* root) {if (root = NULL) return; Deque<bintree*> de; De.push_back (root); int i,level=1; Bintree* Cur,*pre; while (!de.empty ()) {cur = NULL; Pre = NULL; For (I=0;i<level&&!de.empty (); i++) {if (pre = = NULL) {pre = de.fr Ont (); if (pre->left! = NULL) de.push_back (pre->left); if (Pre->right!=null) de.push_back (pre->right); De.pop_front (); cout<<pre->value<<endl; Continue } if (cur = = NULL) {cur = De.front (); if (cur->left! = NULL) de.push_back (cur->left); if (Cur->right!=null) de.push_back (cur->right); De.pop_front (); cout<<cur->value<<endl; Continue } Pre->next =cur; Pre = cur; cur = De.front (); De.pop_front (); if (cur->left! = NULL) de.push_back (cur->left); if (cur->right! = NULL) de.push_back (cur->right); cout<<cur->value<<endl; } if (cur = = null) Pre->next = = NULL; else {pre->next = cur; Cur->next = = NULL; } level *=2; }}
Populating Next right pointers in each Node--leetcode