二叉树的层序遍历
void traverse(Node* root)
{
queue<Node*> q;
Node* temp_node= root;
while(temp_node)
{
cout<<temp_node->value<<endl;
if(temp_node->left)
q.push(temp_node->left);
if(temp_node->right)
q.push(temp_node->right);
if(!q.empty())
{
temp_node = q.front();
q.pop();
}
else
temp_node = NULL;
}
}
上面贴出的代码是我的关卡顺序遍历代码。这段代码对我来说工作得很好,但我不喜欢的一件事是我显式初始化 temp_node = NULL
或者我使用了break。但对我来说这似乎不是一个好的代码。
有没有比这更简洁的实现,或者我怎样才能使这段代码更好?
void traverse(Node* root)
{
queue<Node*> q;
Node* temp_node= root;
while(temp_node)
{
cout<<temp_node->value<<endl;
if(temp_node->left)
q.push(temp_node->left);
if(temp_node->right)
q.push(temp_node->right);
if(!q.empty())
{
temp_node = q.front();
q.pop();
}
else
temp_node = NULL;
}
}
The above posted code is my level order traversal code. This code works fine for me but One thing I dont like is I am explicitly initializing temp_node = NULL
or I use break. But it does not seem to be a good code to me.
Is there a neat implementation than this or how can I make this code better?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
就这样,没有更多的特殊情况了。并且缩进已被清理,因此可以更容易理解。
或者:
作为
for
循环完成。就我个人而言,我喜欢额外的变量。变量名是比一直说“q.front()”更好的速记。There, no more special case. And the indentation is cleaned up so it can be understood more easily.
Alternatively:
Done up as a
for
loop. Personally, I like the extra variable. The variable name is a nicer shorthand than saying 'q.front()` all the time.你可以尝试这样的方法:
You can try this way:
现有代码的一个严重问题是在空树 (
root = NULL
) 上调用它时会崩溃。您需要决定是否要在队列中包含
NULL
指针。如果不是,您只能将非
NULL
值排入队列。或者,如果您决定在队列中包含
NULL
,您可以这样做:第一种方法是首选,因为大树有大量
NULL
子节点(叶节点的子节点),并且那里当我们稍后不处理它们时,将它们排入队列是没有意义的。One serious problem with your existing code is it crashes when it is called on an empty tree (
root = NULL
).You need to decide if you want to have
NULL
pointers in the queue or not.If not them you can only enqueue non-
NULL
values.Alternatively if you decide to have
NULL
in the queue you can do:The first method is preferred as a large tree has plenty of
NULL
children (children of leaf nodes) and there is no point in having them enqueued in the queue when we later just don't process them.尝试:
Try:
我认为上面的代码片段允许以数组格式打印级别顺序遍历。此代码可以帮助以级别顺序的形式编写解决方案。
输出:
I think above code snippets allow to print the level order traversal in array format. This code can help to write the solution in form of level order.
Output:
我的Java解决方案使用队列数据结构和BFS算法:
My Java solution using Queue data structure and BFS algorithm:
以非常简单的方式实现 BST 全序遍历
A BST all order traversal in very simple Way