如何按顺序递归打印二叉树搜索 [英] How to print Binary tree search recursively inorder
问题描述
你好,
我试图在我的标题中实现一个函数,通过inorder方法递归打印二叉树搜索(从中打印每个节点)最低值到最大值)
函数本身不带任何参数
我试图在我自己做的不仅仅是现在几个小时。
我很高兴如果有人能帮我解决这个问题
这些是实现:
Hello there,
I tried to make an implementation of a function in my header that prints recursively by inorder method a binary tree search (printing each node from the lowest value to the biggest)
The function itself do not take any parameters
I tried to do this on my own for more than a few hours now.
I will be happy if anyone could help me figure this out
These are the implementations:
void BSNode::printNodes() const //prints the smallest _data value to the biggest
{
if (_left == NULL)
{
cout << _data << endl;
}
else
{
return _left->printNodes();
}
if (_right == NULL)
{
cout << _data << endl;
}
else
{
return _right->printNodes();
}
}
BSNode::BSNode(string data)
{
_data.clear();
_data.assign(data);
_count=1;
_right = NULL;
_left = NULL;
}
BSNode::BSNode(const BSNode& other)
{
_data.clear();
_data.assign(other._data);
_count = other._count;
_right = other._right;
_left = other._left;
}
BSNode::~BSNode()
{
delete _right;
delete _left;
_data.clear();
_count =0;
}
标题是:
The header is:
class BSNode
{
public:
BSNode(string data);
BSNode(const BSNode& other);
~BSNode();
void insert(string value);
string getData() const;
BSNode* getLeft()const ;
BSNode* getRight() const;
void printNodes() const;//prints the smallest _data value to the biggest
private:
BSNode* _left;
BSNode* _right;
string _data;
int _count;
推荐答案
停一会儿想想你要做什么。
你要做的是拿一个节点,打印它的左图(如果有的话),然后它是正确的图(如果有的话),然后是节点本身:
所以如果你有二叉树:
Stop for a moment and think about what you are trying to do.
What you want to do is take a node, print it's left graph (if any), then it's right graph (if any), then the node itself:
So if you have a binary tree:
1
/ \
2 3
/ / \
4 5 6
你想打印
You want to print
4 2 5 6 3 1
是吗?
你离我不远,但你的代码太早了。尝试一些更简单的东西:
(这是你的作业,所以我不会在这里给你实际的代码)
Yes?
You aren't far off, but your code returns too early. Try something a little simpler:
(This is your homework, so I won't give you actual code here)
node.Print
{
if (n.Left != null) n.Left.Print()
if (n.Right != null) n.Right.Print()
Display(n.Text)
}
我设法找到了一个解决方案.....不知何故......花了我一段时间......
I managed to find a solution.....somehow.... took me a while...
void BSNode::printNodes() const //prints the smallest _data value to the biggest
{
if (_left != NULL)
{
_left->printNodes();
}
cout << _data << endl;
if (_right != NULL)
{
_right->printNodes();
}
这篇关于如何按顺序递归打印二叉树搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!