701.cc 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Definition for a binary tree node.
  2. struct TreeNode {
  3. int val;
  4. TreeNode *left;
  5. TreeNode *right;
  6. TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  7. };
  8. /* BEGIN */
  9. #include <cstdio>
  10. class Solution {
  11. public:
  12. TreeNode* insertIntoBST(TreeNode* root, int val) {
  13. if (root == nullptr) {
  14. return new TreeNode(val); // "new" to avoid freeing memory
  15. }
  16. if (val <= root->val) {
  17. root->left = insertIntoBST(root->left, val);
  18. } else {
  19. root->right = insertIntoBST(root->right, val);
  20. }
  21. return root;
  22. }
  23. };
  24. /* END */
  25. #include <queue>
  26. using std::queue;
  27. void print_tree(TreeNode *root) {
  28. if (root == nullptr) {
  29. printf("null\n");
  30. return;
  31. }
  32. queue<TreeNode *> q;
  33. q.push(root);
  34. TreeNode *curr = nullptr;
  35. int cnt = q.size();
  36. while (q.size() != 0) {
  37. curr = q.front();
  38. q.pop();
  39. cnt--;
  40. printf("%d ", curr->val);
  41. if (curr->left != nullptr) {
  42. q.push(curr->left);
  43. }
  44. if (curr->right != nullptr) {
  45. q.push(curr->right);
  46. }
  47. if (cnt == 0) {
  48. cnt = q.size();
  49. printf("\n");
  50. }
  51. }
  52. }
  53. int main() {
  54. TreeNode n1(1), n2(2), n3(3), n4(4), n7(7);
  55. n2.left = &n1;
  56. n2.right = &n3;
  57. n4.left = &n2;
  58. n4.right = &n7;
  59. TreeNode *root = &n4;
  60. print_tree(root);
  61. root = (new Solution())->insertIntoBST(root, 5);
  62. print_tree(root);
  63. }