Welcome to read the reference, if there are errors or questions, please leave a message to correct, thank you
Populating Next right pointers in each Node II
Follow up to problem "populating Next right pointers in each Node".
What if the given tree could is any binary tree? Would your previous solution still work?
Note:
Constant extra space.
For example,
Given The following binary tree,
1
/ \
2 3
/ \ \
4 5 7
After calling your function, the tree is should look like:
1, NULL
/ \
2, 3, NULL
/ \ \
4-> 5-7, NULL
/** * Definition for binary tree with next pointer. * struct Treelinknode {* int val; * Treelinknode *left, *right, *next; * Treelinknode (int x): Val (x), left (NULL), rig HT (NULL), Next (null) {}}; *///therefore, one node needs to find the first node to the right. For left, if right does not exist, go to the next node of father to find Left/right, and then find it in turn. For right, start looking directly at the next node of father. It is important to note that the right subtree is processed first, and then the left subtree is processed. Class Solution {Treelinknode *node;public:void connect (treelinknode *root) {if (root) {if (RO Ot->left) {if (root->right) Root->left->next = root->right; else {node = root->next; while (node &&!root->left->next) {if (node->left) Root->left->next = node->left; else if (node->right) Root->left->next = node->right; node = node->next; }}} if (Root->right) {node = root->next; while (node && root->right->next==null) {if (node->left) Root->right->next = node->left; else if (node->right) Root->right->next = node->right; node = node->next; }} connect (root->right); Connect (Root->left); } }};
Another way of writing class solution {Public:void connect (Treelinknode *root) {//Start typing your C + + solution below does not write int main () function if (root = NULL) return; Root->next = NULL; treelinknode* prevhead = root; while (true) {treelinknode* cur = prevhead; treelinknode* prev = NULL; while (cur! = null) {if (cur->left! = null) {if (prev! = NUL L) Prev->next = cur->left, prev = prev->next; else prev = cur->left, prevhead = prev; if (cur->right! = null) {if (prev! = null) Prev->next = Cur->ri ght, prev = prev->next; else prev = cur->right, prevhead = prev; } cur = cur->next; } if (prev! = null) Prev->next = NULL; else break; } }};
Leetcode_117_populating Next Right pointers in each Node II