无效移动(节点*根)
{
队列<节点*> q;
节点* temp_node =根;
而(temp_node)
{
COUT<< temp_node->值小于;< ENDL;
如果(temp_node->左)
q.push(temp_node->左);
如果(temp_node->右)
q.push(temp_node->右一);
如果(!q.empty())
{
temp_node = q.front();
q.pop();
}
其他
temp_node = NULL;
}
}
上面贴code是我的水平序遍历code。这code为我工作正常,但有一件事我不喜欢的是,我明确地初始化 temp_node = NULL
或我用休息。但它似乎并没有成为一个好的code给我。
有一个整洁的实现比这个还是我怎样才能使这个code好?
解决方案 无效移动(节点*根)
{
队列<节点*> q;
如果(根){
q.push(根);
}
而(!q.empty())
{
常量节点* const的temp_node = q.front();
q.pop();
COUT<< temp_node->值小于;<\ N的;
如果(temp_node->左){
q.push(temp_node->左);
}
如果(temp_node->右){
q.push(temp_node->右一);
}
}
}
在那里,没有更多的特殊情况。和缩进被清除,因此可以更容易地理解。
或者
无效移动(节点*根)
{
队列<节点*> q;
如果(!根){
返回;
}
对于(q.push(根);!q.empty(); q.pop()){
常量节点* const的temp_node = q.front();
COUT<< temp_node->值小于;<\ N的;
如果(temp_node->左){
q.push(temp_node->左);
}
如果(temp_node->右){
q.push(temp_node->右一);
}
}
}
完成了一个为
循环。就个人而言,我喜欢额外的变量。变量名是一个更好的速记不是说'q.front()`所有的时间。
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?
解决方案void traverse(Node* root)
{
queue<Node*> q;
if (root) {
q.push(root);
}
while (!q.empty())
{
const Node * const temp_node = q.front();
q.pop();
cout<<temp_node->value<<"\n";
if (temp_node->left) {
q.push(temp_node->left);
}
if (temp_node->right) {
q.push(temp_node->right);
}
}
}
There, no more special case. And the indentation is cleaned up so it can be understood more easily.
Alternatively:
void traverse(Node* root)
{
queue<Node*> q;
if (!root) {
return;
}
for (q.push(root); !q.empty(); q.pop()) {
const Node * const temp_node = q.front();
cout<<temp_node->value<<"\n";
if (temp_node->left) {
q.push(temp_node->left);
}
if (temp_node->right) {
q.push(temp_node->right);
}
}
}
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.