LeetCode 701. Insert into a Binary Search Tree
原题链接在这里:https://leetcode.com/problems/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.
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
题解:
If root.val < val, then must insert on root right side, if root right side is already null, then root.right = new TreeNode(val). Otherwise, keep iterating on root.right.
Vice versa.
Time Complexity: O(h). h is height of tree.
Space: O(1).
AC Java:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode() {} 8 * TreeNode(int val) { this.val = val; } 9 * TreeNode(int val, TreeNode left, TreeNode right) { 10 * this.val = val; 11 * this.left = left; 12 * this.right = right; 13 * } 14 * } 15 */ 16 class Solution { 17 public TreeNode insertIntoBST(TreeNode root, int val) { 18 if(root == null){ 19 return new TreeNode(val); 20 } 21 22 TreeNode cur = root; 23 while(cur != null){ 24 if(cur.val < val){ 25 if(cur.right == null){ 26 cur.right = new TreeNode(val); 27 return root; 28 } 29 30 cur = cur.right; 31 }else{ 32 if(cur.left == null){ 33 cur.left = new TreeNode(val); 34 return root; 35 } 36 37 cur = cur.left; 38 } 39 } 40 41 return null; 42 } 43 }
AC C++:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 TreeNode* insertIntoBST(TreeNode* root, int val) { 15 if(!root){ 16 return new TreeNode(val); 17 } 18 19 TreeNode* cur = root; 20 while(cur){ 21 if(cur->val < val){ 22 if(!cur->right){ 23 cur->right = new TreeNode(val); 24 return root; 25 } 26 27 cur = cur->right; 28 }else{ 29 if(!cur->left){ 30 cur->left = new TreeNode(val); 31 return root; 32 } 33 34 cur = cur->left; 35 } 36 } 37 38 return root; 39 } 40 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】博客园2025新款「AI繁忙」系列T恤上架,前往周边小店选购
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步