Created
January 23, 2019 01:41
-
-
Save ttsugriy/85c92ac323f560faea8d3f1d53cf1413 to your computer and use it in GitHub Desktop.
https://leetcode.com/problems/insert-into-a-binary-search-tree (non-recursive)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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