在二叉查找树中插入节点
2017-05-21 09:12
169 查看
问题描述:
给定一棵二叉查找树和一个新的树节点,将节点插入到树中。
你需要保证该树仍然是一棵二叉查找树。
样例
给出如下一棵二叉查找树,在插入节点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) {
// write your code here
if(root==NULL)
{
root=new TreeNode(node->val);
return root;
}
else if(node->val<root->val)
{
root->left=insertNode(root->left,node);
return root;
}
else
root->right=insertNode(root->right,node);
return root;
}
};
做题感想:审完题目,心想就是二叉排序树的插入问题嘛,然后就把课本上的代码打上了,但是没注意到函数的返回类型。
给定一棵二叉查找树和一个新的树节点,将节点插入到树中。
你需要保证该树仍然是一棵二叉查找树。
样例
给出如下一棵二叉查找树,在插入节点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) {
// write your code here
if(root==NULL)
{
root=new TreeNode(node->val);
return root;
}
else if(node->val<root->val)
{
root->left=insertNode(root->left,node);
return root;
}
else
root->right=insertNode(root->right,node);
return root;
}
};
做题感想:审完题目,心想就是二叉排序树的插入问题嘛,然后就把课本上的代码打上了,但是没注意到函数的返回类型。
相关文章推荐
- LintCode(85)在二叉查找树中插入节点
- 在二叉查找树中插入节点
- C++模板实现二叉查找树(一 树的数据结构定义与节点插入)
- 85.在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 算法-二叉查找树-插入节点
- C++模板实现二叉查找树(一 树的数据结构定义与节点插入)
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 算法-二叉查找树-插入节点
- C++模板实现二叉查找树(一 树的数据结构定义与节点插入)
- LintCode 85. 在二叉查找树中插入节点
- [javaSE] 数据结构(二叉查找树-插入节点)
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- C++模板实现二叉查找树(一 树的数据结构定义与节点插入)
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 再二叉查找树中插入节点
- 题目:在二叉查找树中插入节点