在二叉查找树中插入节点
来源:互联网 发布:淘宝买药暗语 编辑:程序博客网 时间:2024/06/10 23:45
一、问题描述
给定一棵二叉查找树和一个新的树节点,将节点插入到树中。
你需要保证该树仍然是一棵二叉查找树。
注意事项
You can assume there is no duplicate values in this tree + node.
给出如下一棵二叉查找树,在插入节点6之后这棵二叉查找树可以是这样的:
2 2 / \ / \1 4 --> 1 4 / / \ 3 3 6
运用递归算法,插入给定节点,用root指针依此遍历二叉树并进行比较,当插入节点小于此时root指针指的节点则继续跟此根节点的左子树进行比较,若大于,再跟右子树比较。
三、我的代码
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) {
// write your code here
if(root==NULL)
{
root=new TreeNode(node->val);
return root;
}
else if(root->val>node->val)
{
root->left=insertNode(root->left,node);
return root;
}
else
{
root->right=insertNode(root->right,node);
return root;
}
}
};
四、我的感想
再次运用递归算法,也说明了递归的重要性,可以大大简化问题,插入节点只需依此遍历二叉树比较大小然后判断插在哪即可。
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- js多物体不同运动
- raphael.js菜鸟笔记(一)
- Gate 7.2的安装与部署(二)
- camera中简易图像转换,图像压缩接口记录
- Activity的生命周期
- 在二叉查找树中插入节点
- IM消息送达保证机制实现
- iOS开发 Xcode使用Analyze静态分析
- Spark一千篇旅游日记0004 之 作业执行解析
- 世界国家中英文对照表(json格式)
- Kudu:支持快速分析的新型Hadoop存储系统
- 嵌入式audio基础(一)接口
- java telnet客户端 用于连接Windows的Telnet服务器
- ECharts地图显示不完整,只显示南海诸岛问题