先序遍历:本身节点,左节点,右节点
思想:想实现中、左、右就需要先压入右,再压入左。
使用栈首先把头节点压入,把头节点弹出,访问;有右节点就把右节点压入,有左节点就把左节点压入;弹出就实现了中, 左, 右
代码实现:
void preOrder(Node* head) {
if (head == NULL) {
return;
}
stack<Node*> st;
st.push(head);
Node* cur;
while (!st.empty()) {
cur = st.top();
st.pop();
cout << cur->value << endl;
if (cur->right != NULL) {
st.push(cur->right);
}
if (cur->left != NULL) {
st.push(cur->left);
}
}
}
中序遍历:左中右
使用栈,当前节点不为空,压入栈且往左走;节点为空,弹出访问,且往右走。
思想:把左中看成整体,左中使用栈遍历之后,然后往右走
void inOrder(Node* head) {
if (head == NULL) {
return;
}
stack<Node*> st;
Node* cur = head;
while (!st.empty() || cur != NULL) {
if (cur != NULL) {
st.push(cur);
cur = cur->left;
}
else {
cur = st.top();
st.pop();
cout << cur->value << endl;
cur = cur->right;
}
}
}
后序遍历:左,右,中
左, 右, 中 不好实现转变成 中, 右,左 的逆序,使用两个栈,一个栈用于实现中,右,左的输出,一个栈由于其逆序
void posOrder(Node* head) {
if (head == NULL) {
return;
}
stack<Node*> s1;//用于实现中,右,左
stack<Node*> s2;//用于实现逆序
Node* cur = head;
s1.push(cur);
while (!s1.empty()) {
cur = s1.top();
s1.pop();
s2.push(cur);
if (cur->left != NULL) {
s1.push(cur -> left);
}
if (cur->right != NULL) {
s1.push(cur->right);
}
}
while (!s2.empty()) {
cout << s2.top()->value << endl;
s2.pop();
}
}