Advertisement
Guest User

Untitled

a guest
Feb 20th, 2020
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.24 KB | None | 0 0
  1. /**
  2.  * Definition for binary tree with next pointer.
  3.  * struct TreeLinkNode {
  4.  *  int val;
  5.  *  TreeLinkNode *left, *right, *next;
  6.  *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
  7.  * };
  8.  */
  9. class Solution {
  10.     TreeLinkNode* jump(TreeLinkNode *root, int i, int j) {
  11.         TreeLinkNode* node = root;
  12.         while (i) {
  13.             int half_width = 1 << (i-1);
  14.             if (j < half_width) {
  15.                 node = node->left;
  16.             } else {
  17.                 node = node->right;
  18.                 j -= half_width;
  19.             }
  20.             i--;
  21.         }
  22.         return node;
  23.     }
  24.    
  25. public:
  26.     void connect(TreeLinkNode *root) {
  27.         TreeLinkNode* node = root;
  28.         int height = 0;
  29.         while (node) {
  30.             height++;
  31.             node = node->left;
  32.         }
  33.        
  34.         TreeLinkNode* leftmost = root;
  35.         for (int i = 0; i < height; i++) {
  36.             int width = 1 << i;
  37.             TreeLinkNode* last = leftmost;
  38.             for (int j = 1; j < width; j++) {
  39.                 node = jump(root, i, j);
  40.                 last->next = node;
  41.                 last = node;
  42.             }
  43.             last->next = NULL;
  44.             leftmost = leftmost->left;
  45.         }
  46.     }
  47. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement