[LeetCode] Insert into a Binary Search Tree 二叉搜索樹中插入結點

 

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.html

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.java

For example, node

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:post

         5
       /   \
      2     7
     / \   
    1   3
         \
          4

 

這道題讓咱們在二叉搜索樹中插入結點,當前還須要保持二叉搜索樹的性質,那麼插入結點的方式就有多種,就像題目中給的那個例子。結點5能夠有不一樣的方法,可是很顯然,放在結點7的左子結點比代替結點4成爲根結點要來的簡單許多。怎麼簡單咱們就怎麼來,因此仍是按照簡單的來吧。因爲二叉搜索樹自帶二分的性質,那麼首先根結點比較,若是大於根結點值的話,說明確定要插入到右子樹中。因此接下來跟7比較,對於遞歸函數來講,結點7也能夠看成是一個新的根結點,那麼因爲結點7的值大於目標值5,因此要去其左子樹,咱們發現其左子結點爲空,那麼咱們就能夠根據目標值來生成一個新的結點,而後連到結點7的左子樹上便可。那麼在遞歸函數中,首先判斷當前結點是否爲空,爲空的話就新建一個結點返回。不然就判斷當前結點值是否大於目標值,是的話就對左子結點調用遞歸函數,並將返回值賦給當前結點的左子結點,不然就對右子結點調用遞歸函數,並將返回值賦給當前結點的右子結點,最後返回當前結點便可,參見代碼以下:this

 

解法一:url

class Solution {
public:
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        if (!root) return new TreeNode(val);
        if (root->val > val) root->left = insertIntoBST(root->left, val);
        else root->right = insertIntoBST(root->right, val);
        return root;
    }
};

 

咱們也能夠不使用遞歸來作,而是用迭代。總體思路跟遞歸併無太大的區別,但沒有遞歸寫法簡潔。首先仍是判空,若爲空,就新建結點返回。而後用一個變量cur來遍歷,在while循環中,若是當前值大於目標值,若是其左子結點不存在,那麼咱們新建結點,並連上其左子結點,並跳出循環;若左子結點存在,則cur指向其左子結點。不然,當前值小於目標值,若其右子結點不存在,新建結點並連上其右子結點,並跳出循環;若右子結點存在,則cur指向其右子結點。最後返回root便可,參見代碼以下:spa

 

解法二:code

class Solution {
public:
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        if (!root) return new TreeNode(val);
        TreeNode *cur = root;
        while (true) {
            if (cur->val > val) {
                if (!cur->left) {cur->left = new TreeNode(val); break;}
                cur = cur->left;
            } else {
                if (!cur->right) {cur->right = new TreeNode(val); break;}
                cur = cur->right;
            }
        }
        return root;
    }
};

 

相似題目:htm

Search in a Binary Search Tree

 

參考資料:

https://leetcode.com/problems/insert-into-a-binary-search-tree/

https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/150757/java-iterative-100

https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/164137/Java-easy-to-understand-solution

 

LeetCode All in One 題目講解彙總(持續更新中...)

相關文章
相關標籤/搜索