/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if (!root) {
TreeNode* node = new TreeNode(val);
return node;
}
if (root->val > val) root->left = insertIntoBST(root->left, val);
if (root->val < val) root->right = insertIntoBST(root->right, val);
return root;
}
};

总结
- 通过递归函数返回值完成了新加入节点的父子关系赋值操作了,下一层将加入节点返回,本层用root->left或者root->right将其接住
这篇博客介绍了如何使用递归方法在二叉搜索树中插入新的节点。代码展示了一个名为`insertIntoBST`的成员函数,该函数根据给定值`val`在树中找到合适的位置插入新节点,并确保树的性质得以保持。递归过程分为三步:1) 如果根节点为空,创建新节点并返回;2) 如果新值小于当前节点值,则在左子树中插入;3) 如果新值大于当前节点值,则在右子树中插入。
258

被折叠的 条评论
为什么被折叠?



