c++ - 迭代插入到二叉搜索树中。调试 C++ 代码

标签 c++ binary-tree

这是一个从整数数组创建 BST 树的 C++ 函数?
很简单。
取第一个元素,生成根。
获取下一个数组元素并将其插入到树中。
为什么循环从 i=2 而不是 i=1 开始??

node* buildtree(int a[], int len)
{
    node* root=new node(a[0]);
    node* temp=root;
    for(int i=1;i<len;i++)
    {
        while(!(root->left==NULL && root->right==NULL))
        {
            cout<<"here"<<i<<" "<<a[i]<<"  " << root->val<<"\n";
            if(root->val>a[i])
                root=root->left;
            else
                root=root->right;
        }
        node* currnode=new node(a[i]);
        if(root->val>a[i]) 
            root->left=currnode;
        else
            root->right=currnode;  

        if(root==NULL)
            cout<<"error...never.here";
        root=temp;
    }
    return root;
}

非常感谢您的解释。我尝试了另一种方法,但它只找到了根。它有什么问题?

   node* buildtree(int a[],int len)
   { node*  root=new node(a[0]);
    node* curr;
    for(int i=1;i<len;i++)
     { curr=root;
       while(curr!=NULL)    
         {
         if(curr->val>a[i])
         curr=curr->left;
         else 
         curr=curr->right;
         }
     curr=new node(a[i]); 
     }  
 return root;             
  }

最佳答案

因为在循环的第一次迭代中,while 条件不成立,因为根节点没有子节点。

while(!(root->left==NULL && root->right==NULL)

对于 i=1,左节点和右节点均为 NULL,左节点在第一次迭代结束时填充。

关于c++ - 迭代插入到二叉搜索树中。调试 C++ 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9367149/

相关文章:

c++ - 比较文本和整数的多个 if 语句

java - 给定完美二叉树,反转二叉树的交替级别节点

recursion - 使用递归计算二叉树的大小

python - 有效地找到二叉树中最重的路径 - python

c++ - 错误 C2143 : syntax error : missing ';' before '*' when declaring pointer

c++ - QFileDialog打开多个文件

c++ - 智能指针所有权语义和平等

python - 递归解析树的所有级别

c++ - 为什么没有 boost::container::queue ?

c++ - OpenGL:我可以将 glBindBuffer 与 glBindBufferARB 混合使用吗?