且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

[LeetCode] Populating Next Right Pointers in Each Node

更新时间:2021-10-25 19:33:39

The idea is similar to a level-order traversal and remember to take full advantages of the prefect binary tree assumption in the problem statement.

The code (iterative solution) is as follows.

 1 class Solution {
 2 public:
 3     void connect(TreeLinkNode *root) {
 4         TreeLinkNode* pre = root;
 5         TreeLinkNode* cur = NULL;
 6         while (pre) {
 7             cur = pre;
 8             while (cur && cur -> left) {
 9                 cur -> left -> next = cur -> right;
10                 if (cur -> next)
11                     cur -> right -> next = cur -> next -> left;
12                 cur = cur -> next;
13             }
14             pre = pre -> left;
15         }
16     }
17 };

This problem can also be solved recursively.

 1 class Solution {
 2 public:
 3     void connect(TreeLinkNode *root) {
 4         if (!root) return;
 5         if (root -> left) {
 6             root -> left -> next = root -> right;
 7             if (root -> next)
 8                 root -> right -> next = root -> next -> left;
 9         }
10         connect(root -> left);
11         connect(root -> right);
12     }
13 };