递归算法
void preorder1(Node *root) //递归前序遍历 { if (root == NULL) return; printf("%d ", root->val); preorder1(root->left); preorder1(root->right); } void inorder1(Node *root) //递归中序遍历 { if (root == NULL) return; inorder1(root->left); printf("%d ", root->val); inorder1(root->right); } void postorder1(Node *root) //递归后序遍历 { if (root == NULL) return; postorder1(root->left); postorder1(root->right); printf("%d ", root->val); }
栈模拟非递归算法。递归算法本质上就是利用编译器实现栈的操作。
void preorder2(Node *root)//非递归前序遍历 { if (root == NULL) return; stack<Node *> stk; stk.push(root); while (!stk.empty()) { Node *p = stk.top(); stk.pop(); printf("%d ", p->val); if (p->right) stk.push(p->right); if (p->left) stk.push(p->left); } }
void postorder2(Node *root)//非递归后序遍历,利用两个栈 { if (root == NULL) return; stack<Node *> stk, stk2; stk.push(root); while (!stk.empty()) { Node *p = stk.top(); stk.pop(); stk2.push(p); if (p->left) stk.push(p->left); if (p->right) stk.push(p->right); } while(!stk2.empty()) { printf("%d ", stk2.top()->val); stk2.pop(); } }
void inorder2(Node *root)//非递归中序遍历 { stack<Node *> stk; Node *p = root; while (p != NULL || !stk.empty()) { if (p != NULL) stk.push(p), p = p->left; else { p = stk.top(); stk.pop(); printf("%d ", p->val); p = p->right; } } }
层次遍历,即从上往下遍历,利用一个队列。
void uptodown(Node *root) { if(root == NULL) return; queue<Node *> Q; Q.push(root) while(!Q.empty()) { Node *p = Q.front(); printf("%d ",p->value); Q.pop(); Q.push(p->left); Q.push(p->right); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-09-29 18:00:24