Insert in BST (LaiCode)

class Solution { public: TreeNode* insert(TreeNode* root, int key) { // write your solution here // iterative if (!root) { root = new TreeNode(key); return root; } TreeNode * ptr = root; while(true){ if (key > ptr->value){ if (ptr->right != nullptr) ptr = ptr->right; else break; } else if (key == ptr->value){ break; } else { if (ptr->left != nullptr) ptr = ptr->left; else break; } } // now break out of the while loop if (key > ptr->value) ptr->right = new TreeNode(key); else if (key < ptr->value) ptr->left = new TreeNode(key); return root; } };
1) Not familiar with the process
2) Not familiar with recursion version. In general not familiar with recursion's return value if the function is not void and pass by reference...

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.