【发布时间】:2020-08-03 18:13:31
【问题描述】:
trav.h
#include <map>
#include <iostream>
class Tree
{
Tree *left;
Tree *right;
int node;
static std::map<int, Tree *> allNodes;
public:
Tree(int n, Tree *l = 0, Tree *r = 0) : left(l), right(r), node(n)
{
allNodes[n] = this;
}
int GetNode() { return node; }
void Insert(Tree *newnode)
{
if (newnode->node == this->node)
{
}
// skip dup
else if (newnode->node < this->node)
{
left = newnode;
cout << "left" << left->node << endl;
}
else if (newnode->node > this->node)
{
right = newnode;
cout << "right" << right->node << endl;
}
}
int Find(int node)
{
if (node == this->node){}
// skip dup
else if (node < this->node)
{
return left->node;
}
else if (node > this->node)
{
return right->node;
}
}
// print does an inorder search
void Print(Tree *root)
{
if (root == nullptr)
{
return;
}
Print(root->left);
cout << root->node << endl;
Print(root->right);
}
};
trav.cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
#include "trav.h"
std::map<int, Tree *> Tree::allNodes;
// trav print
// trav find X
int main(int argc, char *argv[])
{
if (argc < 2)
return 0;
string cmd(argv[1]);
// READ IN THE INTEGERS
vector<int> ids;
int input;
while (cin >> input)
{
ids.push_back(input);
}
// MAKE NODES FROM THE INTEGERS
vector<Tree *> nodes;
for (int id : ids)
{
nodes.push_back(new Tree(id));
}
if (ids.size() == 0)
return -1;
// PUT NODES INTO A TREE USING Insert
Tree *theTree = nodes[0];
if (theTree == nullptr)
return -1;
for (auto n : nodes)
{
theTree->Insert(n);
}
// PRINT TREE
if (cmd == "print")
theTree->Print(theTree);
else if (cmd == "find")
{
string cmd2 = argv[2];
int num = stoi(cmd2);
int result = theTree-> Find(num);
if(result!=0)
cout<<num<<endl;
else
cout<<"-1"<<endl;
}
return 0;
}
在创建 Find() 时遇到问题
- 对树进行中序遍历并打印出遍历
- 在树中找到一个值,如果找到就打印出来
第一个动作在 argv[1] == "print" 时触发。如果是,则进行中序遍历并打印每个树节点,每行输出一个节点。中序遍历是指先遍历左子树(如果存在),然后打印当前节点,再遍历右子树(如果存在)。
第二个动作在 argv[1] == "find" 时触发。如果是这样,请在树中搜索 argv[2](您需要将其转换为 int 的字符串)。如果找到,打印 int。如果没有找到,打印-1。输出格式应该是一行:
【问题讨论】:
-
我不确定您的
Insert成员函数是否有效。在使用Find之前,您是否验证过它有效? -
Find必须遍历树,就像Print一样。所以Find必须递归调用自己(就像Print一样)。你的版本不这样做。 -
你的
Insert函数也有同样的问题。它应该是一个递归例程,但它不是。所以我同意斯蒂芬的观点,在你继续之前让Insert工作。好消息是Print似乎没问题。
标签: c++ binary-tree