我正在尝试使用类在 C++ 中实现一棵树

问题描述

我只是想实现一个 TreeNode 类,它的工作原理类似于树实现的结构节点。

除了在 inorder 遍历开始时包含 0 的输出之外,一切正常。谁能给我解释一下为什么会这样?

输入:

22,1,2,3,5,4,11,20,19,24,21

输出

0 1 2 3 4 5 11 19 20 21 22 24 
#include <bits/stdc++.h>

using namespace std;

class TreeNode{

    public:

        int data;
        TreeNode* left;
        TreeNode* right;

        TreeNode(){
            left = NULL;
            right = NULL;
        }

        TreeNode(int val){
            data = val;
            left = NULL;
            right = NULL;
        }

};

void insertInorder(TreeNode* cur,int d){

    if(d <= cur->data){
        if(cur->left == NULL)
            cur->left = new TreeNode(d);
        else
            insertInorder(cur->left,d);
    }
    else{
        if(cur->right == NULL)
            cur->right = new TreeNode(d);
        else
            insertInorder(cur->right,d);
    }
}

TreeNode* makeTree(vector<int> v){

    TreeNode* root = NULL;

    for(int start = 0; start <= v.size(); start++){
        if(start == 0){
            root = new TreeNode();
            root->data = v[0];
        }
        insertInorder(root,v[start]);
    }

    return root;
}

void printInorder(TreeNode* node) 
{ 
    if (node == NULL) 
        return; 
  
    /* first recur on left child */
    printInorder(node->left); 
  
    /* then print the data of node */
    cout << node->data << " "; 
  
    /* Now recur on right child */
    printInorder(node->right); 
} 

int main(){

    vector<int> x = {22,21};

    TreeNode* r = makeTree(x);

    printInorder(r);


    return 0;

}

编辑:

致将来访问此问题的人。更好的做法表明我们不应该使用

#include <bits/stdc++.h>
using namespace std;

使用命名空间 std 可能会导致代码中未来的命名空间冲突。供参考here。 我犯了同样的错误,但从现在开始我不会这样做了。

请参考@Jabberwocky 提供的链接here

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)