(★★★)二叉樹非遞迴遍歷 (統一的解決思路)
阿新 • • 發佈:2018-11-04
轉載:【刷題】二叉樹非遞迴遍歷
stack<Node*> st; void preOrder(Node* root) { Node *cur = root; while (cur || !st.empty()) { while (cur) { //訪問、入棧、轉向左孩子 pre.push_back(cur->data); st.push(cur); cur = cur->lchild; }if (!st.empty()) { //出棧、轉向右孩子 cur = st.top(); st.pop(); cur = cur->rchild; } } } void inOrder(Node* root) { Node *cur = root; while (cur || !st.empty()) { while (cur) { //入棧、轉向左孩子 st.push(cur); cur= cur->rchild; } if (!st.empty()) { //出棧、訪問、轉向右孩子 cur = st.top(); st.pop(); in.push_back(cur->data); cur = cur->rchild; } } } void postOrder(Node* root) { Node *cur = root, *pre = NULL;//pre指向上一個被訪問過的節點while (cur || !st.empty()) { while (cur) { //入棧、轉向左孩子 st.push(cur); cur = cur->lchild; } if (!st.empty()) { //有條件的出棧, cur = st.top(); // 如果已經訪問了右子樹,則可以訪問根節點;否則轉向,先去訪問右子樹 if (cur->rchild == NULL || cur->rchild == pre) { st.pop(); post.push_back(cur->data); pre = cur; cur = NULL;// 表示不需要轉向,繼續彈棧 } else { //轉向 cur = cur->rchild; } } } }