[LeetCode] 701. Insert into a Binary Search Tree

Description

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.

For 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

Analyse

简单题,将节点插入BST,题目中保证了不会出现值相同的节点

这里用了递归来做,要插入的节点大于root的值,就插入到root的右子树,,否则插入到root的左子树,如果左右子树为空,要插入的节点就成为新的左右子树

TreeNode* insertIntoBST(TreeNode* root, int val)
{
    if (root == NULL) return root;
    InsertIntoBSTInner(root, val);
    return root;
}

void InsertIntoBSTInner(TreeNode* root, int val)
{
    if (root == NULL) return;
    if (val > root->val)
    {
        if (root->right == NULL)
        {
            TreeNode* node = new TreeNode(val);
            root->right = node;
        }
        else
        {
            InsertIntoBSTInner(root->right, val);
        }
    }
    else
    {
        if (root->left == NULL)
        {
            TreeNode* node = new TreeNode(val);
            root->left = node;
        }
        else
        {
            InsertIntoBSTInner(root->left, val);
        }
    }
}

把这段代码简化一下

TreeNode* insertIntoBST(TreeNode* root, int val)
{
    if (root == NULL)
    {
        TreeNode* node = new TreeNode(val);
        return node;
    }

    if (val > root->val)
    {
        root->right = insertIntoBST(root->right, val);
    }
    else
    {
        root->left = insertIntoBST(root->left, val);
    }
    return root;
}
posted @ 2019-01-18 19:43  arcsinW  阅读(158)  评论(0编辑  收藏  举报