本文主要是介绍[力扣题解] 701. 二叉搜索树中的插入操作,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:701. 二叉搜索树中的插入操作
思路
二叉搜索树的查找规律:要插入的值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;}
};
这篇关于[力扣题解] 701. 二叉搜索树中的插入操作的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!