LintCode-在二叉查找树中插入节点
2017-05-18 16:52
225 查看
题目描述:
给定一棵二叉查找树和一个新的树节点,将节点插入到树中。
你需要保证该树仍然是一棵二叉查找树。
注意事项
You can assume there is no duplicate values in this tree + node.
样例:
给出如下一棵二叉查找树,在插入节点6之后这棵二叉查找树可以是这样的:
做题思路:
若二叉查找树为空,则新节点为根节点。若不为空,分情况判断,如果插入节点的值大于根节点的值,则插入右子树,遍历右子树,若不为空,插入新节点;若为空,变成根节点的右儿子。如果插入节点的值小于根节点的值,则插入左子树,遍历左子树,若不为空,插入新节点;若为空,变成根节点的左儿子。插入节点完成后,返回根节点。
关键代码:
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 *root;
TreeNode* insertNode(TreeNode *root, TreeNode* node) {
// write your code here
if(root==NULL)
{
root=node;
return root;
}
if(node->val>root->val)
{
if(root->right==NULL)
root->right=node;
else root->right=insertNode(root->right,node);
}
else
{
if(root->left==NULL)
root->left=node;
else root->left=insertNode(root->left,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
做题思路:
若二叉查找树为空,则新节点为根节点。若不为空,分情况判断,如果插入节点的值大于根节点的值,则插入右子树,遍历右子树,若不为空,插入新节点;若为空,变成根节点的右儿子。如果插入节点的值小于根节点的值,则插入左子树,遍历左子树,若不为空,插入新节点;若为空,变成根节点的左儿子。插入节点完成后,返回根节点。
关键代码:
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 *root;
TreeNode* insertNode(TreeNode *root, TreeNode* node) {
// write your code here
if(root==NULL)
{
root=node;
return root;
}
if(node->val>root->val)
{
if(root->right==NULL)
root->right=node;
else root->right=insertNode(root->right,node);
}
else
{
if(root->left==NULL)
root->left=node;
else root->left=insertNode(root->left,node);
}
return root;
}
};
做题感想:很久没做题,突然做这道题赋值方面就出现了问题,这道题仍旧调用递归函数,进行二叉查找树的插入节点。在判断二叉查找树的条件方面,需要细分。
相关文章推荐
- 【LintCode 简单】85. 在二叉查找树中插入节点
- LintCode 在二叉查找树中插入节点
- lintcode 在二叉查找树中插入节点
- LintCode 在二叉查找树中插入节点
- lintcode-在二叉查找树中插入节点-85
- 在二叉查找树中插入节点-LintCode
- lintcode ----在二叉查找树中插入节点
- Lintcode 85. 在二叉查找树中插入节点
- LintCode 85. 在二叉查找树中插入节点
- LintCode:在二叉查找树中插入节点
- LintCode(85)在二叉查找树中插入节点
- lintcode-85-在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 平衡二叉查找树插入节点操作( AVLTree ):旋转、调整平衡
- 85.在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 再二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点