在二叉查找树中插入节点
2017-05-11 17:39
190 查看
一、问题描述
给定一棵二叉查找树和一个新的树节点,将节点插入到树中。
你需要保证该树仍然是一棵二叉查找树。
注意事项
You can assume there is no duplicate values in this tree + node.
样例
给出如下一棵二叉查找树,在插入节点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;
}
}
};
四、我的感想
再次运用递归算法,也说明了递归的重要性,可以大大简化问题,插入节点只需依此遍历二叉树比较大小然后判断插在哪即可。
给定一棵二叉查找树和一个新的树节点,将节点插入到树中。
你需要保证该树仍然是一棵二叉查找树。
注意事项
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;
}
}
};
四、我的感想
再次运用递归算法,也说明了递归的重要性,可以大大简化问题,插入节点只需依此遍历二叉树比较大小然后判断插在哪即可。
相关文章推荐
- 平衡二叉查找树插入节点操作( AVLTree ):旋转、调整平衡
- 85 - 在二叉查找树中插入节点
- Lintcode 85. 在二叉查找树中插入节点
- LintCode 85-在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点-LintCode
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- LintCode(85)在二叉查找树中插入节点
- 在二叉查找树中插入节点
- lintcode-在二叉查找树中插入节点-85
- lintcode 容易题:Insert Node in a Binary Search Tree 在二叉查找树中插入节点
- C++模板实现二叉查找树(一 树的数据结构定义与节点插入)
- 85.在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 算法-二叉查找树-插入节点
- C++模板实现二叉查找树(一 树的数据结构定义与节点插入)
- 二叉查找树带父节点指针的创建,销毁,查找,删除,插入,找前驱后继,找最小值最大值(递归和非递归的实现)
- LintCode Insert a Node in a Binary Search Tree 在二叉查找树中插入节点