您的位置:首页 > 其它

LintCode-在二叉查找树中插入节点

2017-05-18 16:52 225 查看
题目描述:

给定一棵二叉查找树和一个新的树节点,将节点插入到树中。

你需要保证该树仍然是一棵二叉查找树。


 注意事项


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;
}
};
做题感想:很久没做题,突然做这道题赋值方面就出现了问题,这道题仍旧调用递归函数,进行二叉查找树的插入节点。在判断二叉查找树的条件方面,需要细分。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: