简体   繁体   English

节点插入二叉树C ++

[英]Node insertion binary tree C++

I believe i implemented inserting a new node into a binary search tree, however my testing script shows my tree as being in valid 我相信我实现了将新节点插入二叉搜索树的方法,但是我的测试脚本显示我的树处于有效状态

My code where the value is inserted into the tree if there is no current node. 如果没有当前节点,则将代码插入树中的代码。

bool InsertRecursive(BinaryTreeNode* tree_node, int value) {

 if (tree_node == NULL)
 {

BinaryTreeNode * pNode = new BinaryTreeNode;
pNode->data = value;   // inserting node in
pNode->left_child = NULL;
pNode->right_child = NULL;
tree_node = pNode ; 
return true;
 }
       if(tree_node->data == value )   // if value already exists return false
{
 return false ; 
  }
   else if (tree_node->data > value)   // traverses to find the location for the value
    return InsertRecursive(tree_node->right_child, value);
  else 
return InsertRecursive(tree_node->left_child, value);

 }

the actual method of inserting the node inside 将节点插入其中的实际方法

 bool BinaryTree::Insert(int value) {

if (InsertRecursive(head, value)) {
return true;
} else
  return false;
}

What my testing script says 我的测试脚本怎么说

| | Test: Insert 测试:插入

| | | | -Should be a valid tree of size 1 after inserting '4' -插入“ 4”后应为大小为1的有效树

| | | | | | You built an invalid tree. 您建立了无效的树。 Why would you do that to me? 你为什么要对我这样?

| | | | -Should be a valid tree of size 2 after inserting '2' -插入“ 2”后应为大小为2的有效树

| | | | | | You built an invalid tree. 您建立了无效的树。 Your code needs to get it's life together 您的代码需要一起生活

| | | | -Should be a valid tree of size 3 after inserting '3' -插入“ 3”后应为大小为3的有效树

| | | | | | You built an invalid tree. 您建立了无效的树。 More coffee maybe? 也许再喝咖啡?

| | | | -Insert(1) should return false for: [ d2-1 d1-2 d2-3 d0-4 d2-5 d1-6 d2-7 -Insert(1)对于以下情况应返回false:[d2-1 d1-2 d2-3 d0-4 d2-5 d1-6 d2-7

] | ] | | | | | It returned true. 它返回了true。 Unlike a boss | 不像老板 Failed! 失败了!

So the problem should be with in where i actually insert the node as the tree is being read as in valid. 所以问题应该出在我实际插入节点的位置,因为树被读取为有效。 I am lost on how to solve this however and would like some guidance. 但是,我不知道如何解决此问题,并希望获得一些指导。

when leave fuction, "tree_node = pNode ;" 当离开功能时,“ tree_node = pNode;” effect nothing. 没有效果。 change tree_node type to "BinaryTreeNode**" if you want change it's value 如果要更改其值,请将tree_node类型更改为“ BinaryTreeNode **”

You have to split the inserts into both the helper and the method for each case of when head is equal to nullptr and when tree_node is equal to nullptr . 对于每种情况,当head等于nullptrtree_node等于nullptr时,必须将插入内容分为辅助方法和方法。 Then add your implementations to both of those. 然后将您的实现添加到这两个实现中。

Your insert functions look like they are are on the right track so just think about how the two functions in the helper and the method are similar. 您的插入函数看起来像在正确的轨道上,因此,请考虑一下辅助函数中的两个函数和方法如何相似。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM