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