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
這道題讓我們在二叉搜索樹中插入結點,當前還需要保持二叉搜索樹的性質,那么插入結點的方式就有多種,就像題目中給的那個例子。結點5可以有不同的方法,但是很顯然,放在結點7的左子結點比代替結點4成為根結點要來的簡單許多。怎么簡單我們就怎么來,所以還是按照簡單的來吧。由於二叉搜索樹自帶二分的性質,那么首先根結點比較,如果大於根結點值的話,說明肯定要插入到右子樹中。所以接下來跟7比較,對於遞歸函數來說,結點7也可以當作是一個新的根結點,那么由於結點7的值大於目標值5,所以要去其左子樹,我們發現其左子結點為空,那么我們就可以根據目標值來生成一個新的結點,然后連到結點7的左子樹上即可。那么在遞歸函數中,首先判斷當前結點是否為空,為空的話就新建一個結點返回。否則就判斷當前結點值是否大於目標值,是的話就對左子結點調用遞歸函數,並將返回值賦給當前結點的左子結點,否則就對右子結點調用遞歸函數,並將返回值賦給當前結點的右子結點,最后返回當前結點即可,參見代碼如下:
解法一:
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即可,參見代碼如下:
解法二:
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; } };
類似題目:
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