classSolution { public: TreeNode* insertIntoBST(TreeNode* root, int val){ if (root == nullptr) { return root = new TreeNode(val); }
TreeNode* cur = root, *pre = nullptr; while (cur != nullptr) { pre = cur; if (cur->val > val) cur = cur->left; else cur = cur->right; } if (pre->val > val) pre->left = new TreeNode(val); else pre->right = new TreeNode(val); return root; } };
classSolution { public: TreeNode* insertIntoBST(TreeNode* root, int val){ if (root == nullptr) { return root = new TreeNode(val); }
TreeNode* cur = root; bool flag = 1; while (flag) { while (cur->val < val) { if (cur->right) { cur = cur->right; } else { cur->right = new TreeNode(val); flag = 0; break; } } while (cur->val > val) { if (cur->left) { cur = cur->left; } else { cur->left = new TreeNode(val); flag = 0; break; } } } return root; } };