Skip to content

Instantly share code, notes, and snippets.

@ttsugriy
Created January 23, 2019 01:41
Show Gist options
  • Save ttsugriy/85c92ac323f560faea8d3f1d53cf1413 to your computer and use it in GitHub Desktop.
Save ttsugriy/85c92ac323f560faea8d3f1d53cf1413 to your computer and use it in GitHub Desktop.
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if (root == nullptr) return new TreeNode(val);
TreeNode* prev = nullptr;
for (auto node = root; node != nullptr; ) {
prev = node;
node = val < node->val ? node->left : node->right;
}
auto destination = val < prev->val ? &prev->left : &prev->right;
*destination = new TreeNode(val);
return root;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment