Question 1: populating next right pointers in each node
Given a binary tree
struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; }
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer shoshould be setNULL.
Initially, all next pointers are setNULL.
Note:
- You may only use constant extra space.
- You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children ).
For example,
Given the following perfect binary tree,
1 / 2 3 / \ / 4 5 6 7
After calling your function, the tree shoshould look like:
1 -> NULL / 2 -> 3 -> NULL / \ / 4->5->6->7 -> NULL
Struct treelinknode {int val; treelinknode * left, * right, * Next; treelinknode (int x): Val (x), left (null), right (null ), next (null) {}};/* because the topic describes a Complete Binary Tree, if the next node is not empty, it must be root-> next-> left */class solution {public: void connect (treelinknode * root) {If (! Root | (root-> left = NULL & root-> right = NULL) return; If (root-> left) root-> left-> next = root-> right; if (root-> Right & root-> next) root-> right-> next = root-> next-> left; Connect (root-> left); Connect (root-> right );}};
Question 2: populating next right pointers in each node II
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
The difference is that the binary tree in this question can be in any form. Therefore, you need to find the first node to the right of a node. For left, if right does not exist, find left/right on the next node of Father. For "right", you can directly find it at the next node of Father.
Class solution {public: void connect (treelinknode * root) {If (! Root | (root-> left = NULL & root-> right = NULL) return; treelinknode * P, * q; If (root-> left) {If (root-> right) Root-> left-> next = root-> right; else {q = NULL; P = root-> next; while (P! = NULL) // keep searching for {If (p-> left) {q = p-> left; break;} else if (p-> right) along the parent's next pointer) {q = p-> right; break;} p = p-> next;} root-> left-> next = Q ;}} if (root-> right) {q = NULL; P = root-> next; while (P! = NULL) {If (p-> left) {q = p-> left; break;} else if (p-> right) {q = p-> right; break;} p = p-> next;} root-> right-> next = Q;} connect (root-> right ); // note that the right subtree connect (root-> left) must be constructed first );}};