后序遍历二叉树(递归)
void postOrder(BT* root) {
if (root == NULL)
return;
postOrder(root->lchild);
postOrder(root->rchild);
cout << "Node " << root->num
<< " 's text is " << root->text << endl;
}
后序遍历二叉树(非递归)
记录一下后序遍历非递归写法的步骤:
- 将头结点压入栈;
- 弹出栈顶元素并压入另一个栈;
- 将弹出元素的孩子压入当前栈,先左孩子再右孩子;
- 重复2、3.
void postOrder_stack(BT* root) {
if (root == NULL)
return;
stack<BT*> post1;
stack<BT*> post2;
//将树以 根右左 的顺序压入第二个栈
post1.push(root);
while (!post1.empty()) {
root = post1.top();
post1.pop();
post2.push(root);
if (root->lchild != NULL)
post1.push(root->lchild);
if (root->rchild != NULL)
post1.push(root->rchild);
}
//将第二个栈内的元素一一输出,输出后即是后序排列
while (!post2.empty()) {
root = post2.top();
cout << "Node " << root->num
<< " 's text is " << root->text << endl;
post2.pop();
}
}