Home LeetCode - 701. Insert into a Binary Search Tree
Post
Cancel

LeetCode - 701. Insert into a Binary Search Tree

701. Insert into a Binary Search Tree - medium

문제

Given the root node of a binary search tree (BST) and a value to be inserted into the tree, insert the value into the BST. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.

Note that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.

제한사항

입출력 예

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Example:
Given the tree:
        4
       / \
      2   7
     / \
    1   3
And the value to insert: 5

You can return this binary search tree:

         4
       /   \
      2     7
     / \   /
    1   3 5

This tree is also valid:

         5
       /   \
      2     7
     / \   
    1   3
         \
          4

풀이

  • BST
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        // 현재 노드가 마지막 leaf 까지 왔다면 새 노드 생성
        if (root == NULL)
            return new TreeNode(val); 
        
        // 재귀로 트리를 검색하면서 위치를 찾아감
        // 현재 val이 현재 노드의 크기보다 작으면 left 노드 탐색
        if (val < root->val) 
            root->left = insertIntoBST(root->left, val);
        // 현재 val이 현재 노드의 크기보다 작으면 right 노드 탐색
        else if (val > root->val) 
            root->right = insertIntoBST(root->right, val);

        return root; 
    }
};
This post is licensed under CC BY 4.0 by the author.