中序遍历二叉树(递归)
void inOrder(BT* root) {
if (root == NULL)
return;
inOrder(root->lchild);
cout << "Node " << root->num
<< " 's text is " << root->text << endl;
inOrder(root->rchild);
}
中序遍历二叉树(非递归)
记录一下中序遍历非递归写法的步骤:
- 将树的左边界进栈;
- 弹出栈顶元素并打印;
- 对弹出元素的右结点重复1、2.
void inOrder_stack(BT* root) {
if (root == NULL)
return;
stack<BT*> in;
//将树的左边界进栈
while (root != NULL) {
in.push(root);
root = root->lchild;
}
while (!in.empty()) {
root = in.top();
in.pop();
cout << "Node " << root->num
<< " 's text is " << root->text << endl;
root = root->rchild;
while (root != NULL) {
in.push(root);
root = root->lchild;
}
}
}