1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
class Solution { public: void flatten(TreeNode* root) { flatten_helper(root); }
private: TreeNode *flatten_helper(TreeNode *root) { if (!root || !root->left && !root->right) return root; auto left_last(flatten_helper(root->left)); if (left_last) { left_last->right = root->right; root->right = root->left; root->left = nullptr; } return left_last ? flatten_helper(left_last) : flatten_helper(root->right); } };
|