非递归遍历前序/中序/后续思路一样,只不过是访问根节点的时机不同!!!
1、前序非递归
前序遍历:1 2 4 5 3 6 7 根 左子树 右子树
- 非递归(迭代)访问一棵树
- 访问左路节点并入栈;
- 访问左路节点的右子树(将右子树分成左路节点和右树来访问)
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root)
{
vector<int> ret;
stack<TreeNode*> st;
TreeNode* cur=root;
while(cur || !st.empty())
{
//1、先访问树左路节点
//2、再访问左路节点的右子树
while(cur)
{
ret.push_back(cur->val);
st.push(cur);
cur=cur->left;
}
//取栈中左路节点的右子树出来访问
TreeNode* top=st.top();
st.pop();
cur=top->right;
}
return ret;
}
};
2、中序非递归
- 左路节点入栈;
- 取栈中的节点,访问节点以及访问节点的右子树(右子树通过迭代的方式再分成左路节点和左路节点的右子树的方式访问)
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root)
{
vector<int> ret;
stack<TreeNode*> st;
TreeNode* cur=root;
//循环迭代开始,cur指向节点,就是开始访问这棵树
while(cur || !st.empty())
{
//1、左路节点入栈
while(cur)
{
st.push(cur);
cur=cur->left;
}
//2、取出栈中节点访问,以及访问节点的右子树
TreeNode* top=st.top();
st.pop();
ret.push_back(top->val);
cur=top->right;
}
return ret;
}
};
3、后序非递归