Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在BST中搜索元素_C++_Pointers_Binary Search Tree - Fatal编程技术网

C++ 在BST中搜索元素

C++ 在BST中搜索元素,c++,pointers,binary-search-tree,C++,Pointers,Binary Search Tree,以下是在BST中搜索元素的代码。 有人能解释一下&*cur->right或&*cur->left在代码中的含义吗 多谢各位 TreeNode *insertIntoBST(TreeNode *root, int val) { TreeNode **cur = &root; while( *cur ) cur = (val > (*cur)->val) ? &(*cur)->right : &

以下是在BST中搜索元素的代码。 有人能解释一下&*cur->right或&*cur->left在代码中的含义吗

多谢各位

TreeNode *insertIntoBST(TreeNode *root, int val)
    {
        TreeNode **cur = &root;
        while( *cur )
            cur = (val > (*cur)->val) ? &(*cur)->right : &(*cur)->left;
        *cur = new TreeNode(val);
        return root;
    }
cur是指向指针的指针,因此,要访问它的子元素,需要取消对它的引用*cur,然后才访问元素->左,->右

在右或左得到下一个元素(指针)后,需要将其存储在cur中。但是cur是指向指针的指针,因此您需要使用&if运算符引用

整体表现为丑陋&*cur

顺便说一下,之所以需要指针指向指针,是因为行*cur=new TreeNodeval


如果您只是使用一个指针,那么这一行不会做任何事情,只会更改您的临时指针。由于您使用的是指向指针的指针,因此您正在更改树中的原始节点。

这些属性是当前节点的右和左子级。而while遍历树以找到值的合适位置,因为它比二进制搜索树定义中的当前节点大或小

您能更好地格式化代码吗?它不可读。您应该为BST编写自己的代码,而不是试图理解其他人的代码。有关解释,请参阅。