在二叉查找树中插入节点
2017-05-15 21:03
169 查看
问题描述:
给定一棵二叉查找树和一个新的树节点,将节点插入到树中。
你需要保证该树仍然是一棵二叉查找树。
注意事项
You can assume there is no duplicate values in this tree + node.
样例
给出如下一棵二叉查找树,在插入节点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;
}
};
解题感悟:
找到插入节点的位置是难点,一开始没有想到要保存循环体中的前一个节点。
给定一棵二叉查找树和一个新的树节点,将节点插入到树中。
你需要保证该树仍然是一棵二叉查找树。
注意事项
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;
}
};
解题感悟:
找到插入节点的位置是难点,一开始没有想到要保存循环体中的前一个节点。
相关文章推荐
- C++模板实现二叉查找树(一 树的数据结构定义与节点插入)
- 在二叉查找树中插入节点
- LintCode-在二叉查找树中插入节点
- 在二叉查找树中插入节点
- lintcode ----在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- lintcode 在二叉查找树中插入节点
- LintCode 在二叉查找树中插入节点
- LintCode:在二叉查找树中插入节点
- lintcode-在二叉查找树中插入节点-85
- lintcode 容易题:Insert Node in a Binary Search Tree 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- lintcode-85-在二叉查找树中插入节点
- lintcode insert-node-in-a-binary-search-tree 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 二叉查找树带父节点指针的创建,销毁,查找,删除,插入,找前驱后继,找最小值最大值(递归和非递归的实现)
- LintCode Insert a Node in a Binary Search Tree 在二叉查找树中插入节点