LintCode 在二叉查找树中插入节点
2017-05-21 23:48
169 查看
1.描述
给定一棵二叉查找树和一个新的树节点,将节点插入到树中。
你需要保证该树仍然是一棵二叉查找树。
哪家公司问你的这个题?
Airbnb
Alibaba Amazon
Apple Baidu
Bloomberg Cisco
Dropbox Ebay
Facebook Google
Hulu Intel
Linkedin Microsoft
NetEase Nvidia
Oracle Pinterest
Snapchat Tencent
Twitter Uber
Xiaomi Yahoo
Yelp Zenefits
感谢您的反馈
样例
给出如下一棵二叉查找树,在插入节点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) return node;
if(root->val<=node->val)
{
root->right=insertNode(root->right,node);
}
else
{
root->left=insertNode(root->left,node);
}
return root;
}
};
4.总结
首先根节点和给定值相比较,若节点值大则插入左子树,节点值小则插入右子树。
之后再次和子树的根节点比较大小,递归操作最终找到某个叶子结点,比其小插入
左子树,比其大插入
4000
右子树。
给定一棵二叉查找树和一个新的树节点,将节点插入到树中。
你需要保证该树仍然是一棵二叉查找树。
哪家公司问你的这个题?
Airbnb
Alibaba Amazon
Apple Baidu
Bloomberg Cisco
Dropbox Ebay
Facebook Google
Hulu Intel
Linkedin Microsoft
NetEase Nvidia
Oracle Pinterest
Snapchat Tencent
Twitter Uber
Xiaomi Yahoo
Yelp Zenefits
感谢您的反馈
样例
给出如下一棵二叉查找树,在插入节点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) return node;
if(root->val<=node->val)
{
root->right=insertNode(root->right,node);
}
else
{
root->left=insertNode(root->left,node);
}
return root;
}
};
4.总结
首先根节点和给定值相比较,若节点值大则插入左子树,节点值小则插入右子树。
之后再次和子树的根节点比较大小,递归操作最终找到某个叶子结点,比其小插入
左子树,比其大插入
4000
右子树。
相关文章推荐
- Lintcode 85. 在二叉查找树中插入节点
- LintCode 85. 在二叉查找树中插入节点
- lintcode ----在二叉查找树中插入节点
- LintCode:在二叉查找树中插入节点
- LintCode(85)在二叉查找树中插入节点
- lintcode-85-在二叉查找树中插入节点
- 【LintCode 简单】85. 在二叉查找树中插入节点
- lintcode-在二叉查找树中插入节点-85
- LintCode-在二叉查找树中插入节点
- lintcode 在二叉查找树中插入节点
- LintCode 在二叉查找树中插入节点
- 在二叉查找树中插入节点-LintCode
- LintCode 87-删除二叉查找树的节点
- 在二叉查找树中插入节点
- C++模板实现二叉查找树(一 树的数据结构定义与节点插入)
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- C++模板实现二叉查找树(一 树的数据结构定义与节点插入)
- 二叉排序树(二叉查找树)BST构造,节点插入,节点查找,节点删除(java)
- 在二叉查找树中插入节点