# 循环遍历二叉树

2016/10/25 15:14

``````struct Node
{
Node*left;
Node*right;
int data;
Node(){ func; }
};

Node* create(Node*p, int depth)
{
if (p && depth)
{
p->left = new Node;
p->right = new Node;
p->data = depth;
create(p->left, depth - 1);
create(p->right, depth - 1);

}
if (!depth)
{
p->left = nullptr;
p->right = nullptr;
p->data = depth;

}

return p;

}

void print1(Node*p)
{
if (p)
{
cout << p->data << " ";
print1(p->left);
print1(p->right);
}
}

{
stack<Node* > s;

{
while (p)
{
s.push(p);
cout << p->data << " ";
p = p->left;
}

while (!s.empty())
{
Node*pp = s.top();

if (pp->right && pp != head)
{
cout << pp->right->data << " ";
}
s.pop();
}

}

{

while (p)
{
s.push(p);
cout << p->data << " ";
p = p->left;
}

while (!s.empty())
{
Node*pp = s.top();

if (pp->right
{
cout << pp->right->data << " ";
}
s.pop();
}

}

}

int main()
{

cout << endl;

system("pause");
return 0;
}

``````

``````
{
stack<Node* > s;

{
while (p)
{
s.push(p);
//	cout << p->data << " ";
p = p->left;
}

while (!s.empty())
{
Node*pp = s.top();
cout << pp->data << " ";

if (pp->right && pp != head  )
{

cout << pp->right->data << " ";
}
s.pop();
}

}

{

while (p)
{
s.push(p);

p = p->left;
}

while (!s.empty())
{
Node*pp = s.top();
cout << pp->data << " ";
{
cout << pp->right->data << " ";
}
s.pop();
}

}

}``````

``````
{
stack<Node* > s;

{
while (p)
{
s.push(p);

p = p->left;
}

while (!s.empty())
{
Node*pp = s.top();
if (pp->right && pp != head  )
{

cout << pp->right->data << " ";
}
cout << pp->data << " ";
s.pop();
}

}

{

while (p)
{
s.push(p);
p = p->left;
}

while (!s.empty())
{
Node*pp = s.top();

{
cout << pp->right->data << " ";
}
cout << pp->data << " ";
s.pop();
}

}
cout << head->data << " ";
}``````

0
0 收藏

0 评论
0 收藏
0