[ 二叉树 ] 二叉搜索树中的插入操作
程序员文章站
2022-05-16 11:26:19
...
701. 二叉搜索树中的插入操作 - 力扣(LeetCode) (leetcode-cn.com)
二叉搜索树中的插入操作
递归
- 多说一句: Leetcode提供的默认函数并不是确定的, 我们函数的返回值和参数需要我们自己思考。
- 比如,我们要插入一个结点,我们要找到新结点,此处是null;我们要找到位置的父结点。
- 此时我们在找到结点时返回父结点就很简单。所以我们要根据我们要干什么先确定参数和返回值
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;
}
};
非递归
- BST的操作通常非递归方法更好理解
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
// 构造插入节点
TreeNode* node = new TreeNode(val);
if (!root) return node;
TreeNode* cur = root;
TreeNode* parent = root;
// 找到插入节点
while (cur) {
parent = cur;
if (cur->val > val) cur = cur->left;
else cur = cur->right;
}
// 判断插入的结点是左孩子还是右孩子
if (val < parent->val) parent->left = node;
else parent->right = node;
return root;
}
};
上一篇: [ 二叉树 ] 删除搜索二叉树中的结点
下一篇: opencv convertTo函数详解