在二叉树的前序遍历的非递归算法(一)中使用的算法是比较烦的,下面介绍一下较简单点的算法,理解起来更容易。
前序遍历是先遍历根结点,然后分别是左、右结点,对于左右子树使用同样的思想,那么我们可以使用一个堆栈,一开始将根结点压入堆栈,然后开始循环,先将堆栈顶元素弹出,然后访问,然后依次将其右结点和左结点压入堆栈,注意是先右后左而不是先左后右。此过程直到堆栈为空。
算法实现如下:
- void preOrderIter(struct node *root)
- {
- if (root == NULL) return;
- stack<struct node *> s;
- s.push(root);
- while (!s.empty()) {
- struct node *nd = s.top();
- cout << nd->data << " ";
- s.pop();
- if (nd->right != NULL)
- s.push(nd->right);
- if (nd->left != NULL)
- s.push(nd->left);
- }
- cout << endl;
- }