C 二叉树中的插入
如何递归地在二叉树中执行插入,使其始终从左侧填充???下面是我写的代码,这当然是错误的…我在递归方面有点弱…请提供您的建议C 二叉树中的插入,c,binary-tree,C,Binary Tree,如何递归地在二叉树中执行插入,使其始终从左侧填充???下面是我写的代码,这当然是错误的…我在递归方面有点弱…请提供您的建议 void insert(node **root,int n) { node *temp; temp=(node *)malloc(sizeof(node)); temp->data=n; temp->lchild=NULL; temp->rchild=NULL; if(*root==NULL)
void insert(node **root,int n)
{
node *temp;
temp=(node *)malloc(sizeof(node));
temp->data=n;
temp->lchild=NULL;
temp->rchild=NULL;
if(*root==NULL)
{
*root=temp;
return;
}
if((*root)->lchild==NULL)
{
(*root)->lchild=temp;
return;
}
if((*root)->rchild==NULL)
{
(*root)->rchild=temp;
return;
}
insert(&((*root)->lchild),n);
insert(&((*root)->rchild),n);
return;
}
n
插入到这两个子树中尝试迭代的方法。否则,正如上面的用户所建议的,你将得到一个类似左->左->左等的列表 如果您以迭代的方式使用一种方法
public void insert(String data)
{
if(node == null)
node = new Node(null,data,null);
else
{
Queue<Node> q = new LinkedList<Node>();
q.add(node);
while(q.peek() != null)
{
Node temp = q.remove();
if(temp.left != null)
q.add(temp.left);
else
{
temp.left = new Node(null,data,null);
break;
}
if(temp.right != null)
{
q.add(temp.right);
}
else
{
temp.right = new Node(null,data,null);
break;
}
}
}
}
public void插入(字符串数据)
{
if(node==null)
节点=新节点(空,数据,空);
其他的
{
队列q=新的LinkedList();
q、 添加(节点);
while(q.peek()!=null)
{
节点温度=q.remove();
如果(左侧温度!=null)
q、 添加(左侧温度);
其他的
{
temp.left=新节点(null,data,null);
打破
}
如果(临时正确!=null)
{
q、 添加(右侧温度);
}
其他的
{
temp.right=新节点(null,data,null);
打破
}
}
}
}
上面的代码是用Java编写的。我想这在C语言中很容易实现。你需要知道树中有多少元素来平衡它-或者你只需要得到一个列表(左->左->左->左等)。告诉我们树应该是平衡的、完整的还是搜索二叉树。插入策略会有所不同。它只是一个二叉树……因此,在插入时,您需要跟踪二叉树的策略……有必要强制转换malloc的返回值,因为malloc总是返回一个空指针……是的,它在两个子树中都插入了n……如何修改它???否。只有当您有<代码>包含了错误,或者如果使用C++编译器。作为对代码的修改或修复,@sje397在上面的评论中有一个很好的建议。您需要决定在哪个子树中插入新节点,而不是将其同时放入这两个子树中。