思路
二叉搜索树的查找规律:要插入的值val
比当前节点大,往右走,比当前节点小,往左走;
代码
Method 1
class Solution {
public:
void travel(TreeNode* cur, int val)
{
if(cur == NULL)
{
return;
}
if(cur->val > val)
{
if(cur->left)
{
travel(cur->left, val);
}
else // == NULL
{
TreeNode* temp = new TreeNode(val);
cur->left = temp;
}
}
if(cur->val < val)
{
if(cur->right)
{
travel(cur->right, val);
}
else
{
TreeNode* temp = new TreeNode(val);
cur->right = temp;
}
}
}
TreeNode* insertIntoBST(TreeNode* root, int val)
{
if(root == NULL)
{
TreeNode* temp = new TreeNode(val);
root = temp;
return root;
}
travel(root, val);
return root;
}
};
Method 2
class Solution {
public:
TreeNode* travel(TreeNode* cur, int val)
{
if(cur == NULL)
{
TreeNode* node = new TreeNode(val);
return node;
}
if(val < cur->val)
{
cur->left = travel(cur->left, val);
}
if(val > cur->val)
{
cur->right = travel(cur->right, val);
}
return cur;
}
TreeNode* insertIntoBST(TreeNode* root, int val) {
root = travel(root, val);
return root;
}
};