Leetcode 701. Insert into a Binary Search Tree

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Insert into a Binary Search Tree

2. Solution

  • Iterative
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
28
29
30
31
32
33
34
35
36
37
/**
* 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) {
TreeNode* insert = new TreeNode(val);
if(!root) {
root = insert;
return root;
}
TreeNode* current = root;
TreeNode* pre = NULL;
while(current) {
pre = current;
if(current->val > val) {
current = current->left;
}
else {
current = current->right;
}
}
if(pre->val > val) {
pre->left = insert;
}
else {
pre->right = insert;
}
return root;
}
};
  • Recursive
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
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* 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) {
TreeNode* insert = new TreeNode(val);
if(!root) {
root = insert;
return root;
}
insertNodeIntoBST(root, val);
return root;
}

void insertNodeIntoBST(TreeNode* root, int val) {
if(root->val > val) {
if(!root->left) {
root->left = new TreeNode(val);
}
else {
insertNodeIntoBST(root->left, val);
}
}
else {
if(!root->right) {
root->right = new TreeNode(val);
}
else {
insertNodeIntoBST(root->right, val);
}
}
}
};

Reference

  1. https://leetcode.com/problems/insert-into-a-binary-search-tree/description/
如果有收获,可以请我喝杯咖啡!