在二叉查找树中插入节点
来源:互联网 发布:有深度的书籍推荐知乎 编辑:程序博客网 时间:2024/05/29 18:34
问题描述:
给定一棵二叉查找树和一个新的树节点,将节点插入到树中。
你需要保证该树仍然是一棵二叉查找树。
注意事项
You can assume there is no duplicate values in this tree + node.
样例
给出如下一棵二叉查找树,在插入节点6之后这棵二叉查找树可以是这样的:
2 2 / \ / \1 4 --> 1 4 / / \ 3
3 6
解题思路:
二叉查找树的特点是左子树上节点的数值都小于根节点的数值,右子树上节点的数值都大于等于根节点的数值。插入节点的关键是找到插入节点的位置,即判断插入节点的数值与树的节点上数值的大小的关系,当找到插入节点的位置后直接将插入的节点放入树中返回root即可。从根节点开始建立循环,比较插入节点的数值与树上节点值得大小。插入节点值为t,如果t小于根节点的数值,则插入节点的位置在左子树,否则在右子树,依次向下循环直到叶子节点。新建节点pre用以保存前面的节点,退出循环后的pre节点就是插入的位置。
代码实现:
/**
* 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) return node;
if(node==NULL) return root;
int t=node->val;
TreeNode* p=root;
TreeNode* pre=p;
while(p!=NULL){
pre=p;
if(t>=p->val){
p=p->right;
}
else
p=p->left;
}
if(pre->val>t)
pre->left=node;
if(pre->val<=t)
pre->right=node;
return root;
}
};
解题感悟:
找到插入节点的位置是难点,一开始没有想到要保存循环体中的前一个节点。
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- linux screen 命令详解
- [从面试题看问题]线程篇(一)
- 互联网产品经理成长记
- iOS开发——性能优化
- tomcat目录结构
- 在二叉查找树中插入节点
- XTU 1264 Partial Sum【思维+贪心】
- Java面向对象
- HDU 2818 Building Block (带权并查集)
- Servlet的生命周期与浏览器访问Servlet
- 95. Unique Binary Search Trees II
- 微服务,微架构[五]之springboot读取properties文件
- View的测量
- |算法讨论|树链剖分 学习笔记