在二叉查找树中插入节点
来源:互联网 发布:ps4数据库损坏 编辑:程序博客网 时间:2024/05/16 08:14
问题描述:
给定一棵二叉查找树和一个新的树节点,将节点插入到树中。
你需要保证该树仍然是一棵二叉查找树。
样例给出如下一棵二叉查找树,在插入节点6之后这棵二叉查找树可以是这样的:
2 2 / \ / \1 4 --> 1 4 / / \ 3 3 6
运用递归调用和查找树的特点,值比根节点大的在左子树,比根节点小的在右子树
代码:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of the binary search tree.
* @param node: insert this node into the binary search tree
* @return: The root of the new binary search tree.
*/
TreeNode* insertNode(TreeNode* root, TreeNode* node) {
if(root==NULL) return node;
else
if(root->val<=node->val)
root->right=insertNode(root->right,node);
else
root->left=insertNode(root->left,node);
return root;
// write your code here
}
};
感想:
注意要把递归的结果记录下来
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- MailBee.NET Objects发送电子邮件(SMTP)教程七:添加多个附件
- 机器学习中过拟合问题
- 阿里云ECS Centos开启ipv6支持
- ECMAScript 6(12)函数的扩展(1)——函数参数的默认值之详细解析
- 使用RecyclerView中引发 java.lang.IllegalStateException: Cannot call this method while RecyclerView is com
- 在二叉查找树中插入节点
- redis 相关命令
- 【Android7.1.2源码解析系列】实战分析init.rc文件
- Kotlin学习!!!此帖有点火
- JVM调优总结(七)-典型配置举例1
- Activity的生命周期
- EOJ-3218 思维 + STL
- 验证码/密码按位分割输入框
- 乘法逆元总结(求法及递推式)