您的位置:首页 > 理论基础 > 数据结构算法

树的前序遍历非递归、中序遍历非递归、后序遍历非递归

2016-04-06 22:49 465 查看
1、二叉树前序遍历非递归

//前序遍历非递归
std::vector<int> PreOrder(TreeNode *root) {
std::vector<int> ans;
if (root == NULL)
return ans;
std::stack<TreeNode *> stk;
TreeNode *p = root;
while (p != NULL || !stk.empty()) {
if (p != NULL) {
stk.push(p);
ans.push_back(p->val);
p = p->left;
}
else {
p = stk.top();
stk.pop();
p = p->right;
}
}
return ans;
}

2、二叉树中序遍历非递归
//中序遍历非递归
std::vector<int> PreOrder(TreeNode *root) {
std::vector<int> ans;
if (root == NULL)
return ans;
std::stack<TreeNode *> stk;
TreeNode *p = root;
while (p != NULL || !stk.empty()) {
if (p != NULL) {
stk.push(p);
p = p->left;
}
else {
p = stk.top();
stk.pop();
ans.push_back(p->val);
p = p->right;
}
}
return ans;
}

3、二叉树后序遍历非递归
//后续遍历非递归
std::vector<int> PreOrder(TreeNode *root) {
std::vector<int> ans;
if (root == NULL)
return ans;
std::stack<TreeNode *> stk;
TreeNode *p = root;
TreeNode *already = NULL; //记录上一次访问过的节点
while (p != NULL || !stk.empty()) {
if (p != NULL) {
stk.push(p);
p = p->left;
}
else {
p = stk.top();
//转向右子树
if (p->right != NULL && p->right != already) {
p = p->right;
stk.push(p);
p = p->left; //再走向左下
}
else {
p = stk.top();
stk.pop();
ans.push_back(p->val);
already = p; //将当前访问过的节点标记为already
p = NULL; //重要,因为一定是从栈上弹出节点
}
}
}
return ans;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息