在二叉查找树中插入节点
来源:互联网 发布:ug8.0数控编程实例 编辑:程序博客网 时间:2024/05/17 10:06
1.问题描述
给定一棵二叉查找树和一个新的树节点,将节点插入到树中。
你需要保证该树仍然是一棵二叉查找树。
注意事项
You can assume there is no duplicate values in this tree + node.
给出如下一棵二叉查找树,在插入节点6之后这棵二叉查找树可以是这样的:
2 2 / \ / \1 4 --> 1 4 / / \ 3 3 6
2.解题思路
如果树为空,直接生成一棵只有根节点的树,树不为空时,判断节点与根节点的大小,然后按大小递归左右子树,最后返回头结点。
3.代码实现
/**
* 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) {
// write your code here
if(root==NULL)
{ root=new TreeNode(node->val);
return root;
}
if(node->val>root->val)
{
root->right=insertNode(root->right,node);
return root;
}
if(node->val<root->val)
{
root->left=insertNode(root->left,node);
return root;
}
}
};
4.感想
注意在递归时,根据前提条件将递归结果复制给当前节点的左右子树。
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 笔记——过滤器与包装器
- Top-push Video-based Person Re-identification
- Python中的isinstance函数
- 新路程------imx6 uart和串口(4)
- DB2数据库 SQL语句判断两个日期 是否属于同一个季度
- 在二叉查找树中插入节点
- 使用Nexus搭建Maven私服
- python爬虫练习--爬取某城市历史气象数据(待优化)
- 第二章算法
- 计算机控制系统中的抗干扰技术
- Socket通信
- bzoj1616
- Latex Error “Font txsy at 540 not found“
- java编程思想(一)