private: TreeNode* flattenTreeNode(TreeNode* root){ if (root == nullptr) returnnullptr; if (!root->left && !root->right) return root;
// store left & right subtree to a local var incase we lost it TreeNode* left = root->left; TreeNode* right = root->right;
// flattern left subtree, if left is nullptr, the end of left subtree // would be root TreeNode* left_end = root; if (left) left_end = flattenTreeNode(left);
// flatten right subtree, if right is nullptr, // the end of right subtree would be the end of left subtree TreeNode* right_end = left_end; if (right) right_end = flattenTreeNode(right);
// detach left subtree root->left = nullptr; // attach left flattened subtree to right of root root->right = left; // concatanate right flatterned subtree to the end of left flattened // subtree left_end->right = right;