题目:
给定二叉搜索树(BST)的根节点和要插入树中的值,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 输入数据 保证 ,新值和原始二叉搜索树中的任意节点值都不同。
注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回 任意有效的结果
/**
* 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)
// {
// // 遍历整颗搜索树简直是对搜索树的侮辱,哈哈。
// // 终止条件: 遇到空节点就 new一个新的节点,并返回
// if(root == nullptr)
// {
// // 第一条:不知道要 new 一个新的节点,
// // 第二条:这个node 怎么和 root 联系起来呢?
// // 啊 ~ 原来是通过 return 联系起来哦 ~
// 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;
// }
// /******法二:递归函数不用返回值,也可以找到插入的节点位置,直接让父节点指向插入节点,结束递归****/
// // 没有返回值,就需要记录上一个节点(parent),遇到空节点了,
// // 就让parent左孩子或者右孩子指向新插入的节点
// TreeNode* parent;
// void traversal(TreeNode* cur, int val)
// {
// // 终止条件
// if(cur == nullptr)
// {
// // 因为在主函数中对 root 根节点做了空节点的处理,因此,parent 一定不会是野指针
// TreeNode* node = new TreeNode(val);
// if(val > parent->val)
// {
// parent->right = node;
// }
// else
// {
// parent->left = node;
// }
// return;
// }
// // 单层递归逻辑
// // 这里更新父节点。
// parent = cur;
// if(cur->val > val)
// {
// traversal(cur->left, val);
// }
// if(cur->val < val)
// {
// traversal(cur->right, val);
// }
// return;
// }
// TreeNode* insertIntoBST(TreeNode* root, int val)
// {
// // parent = new TreeNode(0);
// if(root == nullptr)
// {
// root = new TreeNode(val);
// return root;
// }
// traversal(root, val);
// return root;
// }
/***********************法三::迭代法******************************/
TreeNode* insertIntoBST(TreeNode* root, int val)
{
if(root == nullptr)
{
root = new TreeNode(val);
return root;
}
TreeNode* cur = root;
TreeNode* parent = root; // 记录上一个节点
// 注意逻辑上是要找到一个 符合条件的空节点 才开始创建新的节点
while(cur != nullptr)
{
parent = cur;
if(cur->val > val)
{
cur = cur->left;
}
// ***********************这里写成 if(cur->val < val) 就是错的
else
{
cur = cur->right;
}
}
//走到这一步就是找到了 符合条件的空节点
TreeNode* node = new TreeNode(val);
// 因为此时当前节点是满足条件的空节点,所以要分辨一下这个新节点是left 或 right
// 因此要用到 上一个节点
if(parent->val > val)
{
parent->left = node;
}
else
{
parent->right = node;
}
// 这个方法中的两个判断 都是 if-else 结构就够用,因为题上说明了不会有相等的节点值
return root;
}
};