Advertisement
pb_jiang

mock interview

Oct 23rd, 2024
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.86 KB | None | 0 0
  1. class Solution {
  2.     using n2t = array<Node*, 2>;
  3.     n2t traverse(Node* node) {
  4.         if (node == nullptr) return {nullptr, nullptr};
  5.         auto r1 = traverse(node->left);
  6.         auto r2 = traverse(node->right);
  7.         if (r1[0] != nullptr) {
  8.             r1[1]->right = node;
  9.             node->left = r1[1];
  10.         } else {
  11.             node->left = nullptr;
  12.         }
  13.  
  14.         if (r2[0] != nullptr) {
  15.             node->right = r2[0];
  16.             r2[0]->left = node;
  17.         } else {
  18.             node->right = nullptr;
  19.         }
  20.  
  21.         return {r1[0] != nullptr ? r1[0] : node, r2[0] != nullptr ? r2[1] : node};
  22.     }
  23. public:
  24.     Node* treeToDoublyList(Node* root) {
  25.         if (root == nullptr) return root;
  26.         auto ret = traverse(root);
  27.         ret[0]->left = ret[1];
  28.         ret[1]->right = ret[0];
  29.         return ret[0];
  30.     }
  31. };
  32.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement