一直觉得非递归遍历树也很简单,就一直没有写,小问题栽了大跟头啊,继续努力吧。
这里说一下非递归的思想主要是怎么做,使用栈空间和使用递归比较像,但是有一些细节不一样,因为while循环可能在后序遍历的时候重复压栈。
下面写一下三种遍历的代码:
- 先序遍历
void preorderTree(TreeNode * root){
stack<TreeNode *> st;
TreeNode * temp = root;
while (temp != NULL || !st.empty()) {
while (temp != NULL) {//每次把左子树全部压进去
st.push(temp);
cout<<st.top()->val<<endl;//压栈的时候就输出
temp = temp->left;
}
if (!st.empty()) {//左子树已经压完了 找到右子树
temp = st.top()->right;//输出完找到右孩子
st.pop();
}
}
}
- 中序遍历
void inorderTree(TreeNode * root){
stack<TreeNode *> st;
TreeNode * temp = root;
while (temp != NULL || !st.empty()) {
while (temp != NULL) {
st.push(temp);
temp = temp->left;
}
if (!st.empty()) {
cout<<st.top()->val<<endl;
temp = st.top()->right;
st.pop();
}
}
}
- 后序遍历
void nextorderTree(TreeNode * root){
stack<TreeNode *> st;
TreeNode * temp = root;
while (temp != NULL || !st.empty()) {
while (temp != NULL) {
st.push(temp);
if (temp->left == NULL) {
temp = temp->right;
}else{
temp = temp->left;
}
}
while (!st.empty() && temp == st.top()->right) {
temp = st.top();
cout<<temp->val<<endl;
st.pop();
}
if (!st.empty()) {
temp = st.top()->right;
}else{
temp = NULL;
}
}
}
这里主要解释一下后序遍历,压栈的时候,我把左子树和右子树全部都压到栈里了。这个时候先左后右再中间,那么遇到一个问题,就是弹栈的时候,如果只弹了一次,可能会出现while循环会再次压右子树的情况,所以一次把栈里面所有右节点都弹出来,直到判断到弹出的元素是栈顶元素的左孩子为止。