TreeNode* insertNode(TreeNode* root, TreeNode* node)
{
// write your code here
if(root==NULL) //为空则把node赋值给root
{
root=node;
return root;
}
TreeNode *head = root; //记录根节点
while(root!=NULL)
{
if(node->val<root->val)//比root节点小,则判断左边
{
if(!root->left)//无左节点,把node赋值给root->left
{
root->left=node;
return head;
}
root=root->left;//否则把root->left赋值给root,继续判断
}
else
{
if(!root->right)//无右节点,把node赋值给root->right
{
root->right=node;
return head;
}
root=root->right; //否则把root->right赋值给root,继续判断
}
}
}
lintcode ----在二叉查找树中插入节点
最新推荐文章于 2023-09-14 10:36:20 发布