typedef struct NodeType{ int data; struct NodeType* left; struct NodeType* right; NodeType(){left = NULL;right = NULL;}; }Node; const int MAX = 100; Node* stack[MAX]; int top = -1; int tag[MAX];
1 前序遍历
从根节点开始的所有的左结点依次入栈,然后从root的左子树的左叶子结点开始回溯,那么此左叶子结点一定没有左子结点,可能会有右子结点。该回溯节点出栈后,将它的右子结点当作根结点,重复上述动作。
void PreOrder(Node* root) { while (NULL != root || top >= 0) { while (NULL != root) { cout << root->data << endl; top++; stack[top] = root; root = root->left; } //从root的左子树的左叶子节点开始回溯 if (top >= 0) { Node* cur = stack[top]; top--;//回溯完后即出栈 root = cur->right; } } }
void InOrder(Node* root) { while (NULL != root || top >= 0) { while (NULL != root) { top++; stack[top] = root; root = root->left; } //从root的左子树的左叶子节点开始回溯 if (top >=0) { Node* cur = stack[top]; cout << cur->data << endl; top--;//回溯完后即出栈 root = cur->right; } } }
void PostOrder(Node* root) { while (NULL != root || top >= 0) { while (NULL != root) { top++; stack[top] = root; tag[top] = 0;//默认root的右节点没有访问过(算法保证回溯到root时,则它的左节点一定是访问过的) root = root->left; } //从roo的t左子树的左叶子节点开始回溯 if (top >= 0) { Node* cur = stack[top]; if (1 == tag[top]) { cout << cur->data << endl; top--;//第二次回溯到该节点后出栈 } else { //第一回溯到该节点暂时不出栈 root = cur->right; tag[top] = 1;//标识root的右节点已经访问过 } } } }