Leetcode 701. Insert into a Binary Search Tree(BST)


题目来源:https://leetcode.com/problems/insert-into-a-binary-search-tree/description/

标记难度:Easy

提交次数:1/1

代码效率:15.50%

题意

在二叉搜索树中插入元素。

分析

感觉和Leetcode 700是同一系列的题目。同样直接插入就可以了。

代码

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
/**
* 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) {
if (root == NULL)
return new TreeNode(val);
TreeNode* p = root;
while (p != NULL) {
if (val < p->val) {
if (p->left == NULL) {
p->left = new TreeNode(val);
break;
}
p = p->left;
}
else {
if (p->right == NULL) {
p->right = new TreeNode(val);
break;
}
p = p->right;
}
}
return root;
}
};

 评论