首页 > 代码库 > 二叉树遍历 非递归算法
二叉树遍历 非递归算法
mooc的作业本来以为是很简单,真正写下去才知道不简单。
每个都略有技巧,细细琢磨
#include <cstdio>#include <cstring>int all, top;class TreeNode{ public: int value; TreeNode* left; TreeNode* right; TreeNode(int _value, TreeNode *_left, TreeNode *_right) { value = _value; left = _left; right = _right; }};TreeNode *stack[105];int result[105];void preorderTraversal(TreeNode *root, int *result)// 前序遍历{ top = all = 0; if(root != NULL) stack[top++] = root;// 根节点入栈 while(top > 0) { TreeNode* now = stack[--top]; result[all++] = now->value; if(now -> right != NULL) stack[top++] = now->right;// 插入右节点 if(now -> left != NULL) stack[top++] = now->left;// 插入左节点 }}void inorderTraversal(TreeNode *root, int *result)// 中序遍历{ top = all = 0; TreeNode* now = root; while(1) { while(now != NULL)// 先到最左边的儿子 { stack[top++] = now;// 父节点入栈 now = now->left; } if(top == 0) break; now = stack[--top];// 若无右儿子取父亲 result[all++] = now->value; now = now->right;// 先右儿子 }}void postorderTraversal(TreeNode *root, int *result)// 后序遍历{ top = all = 0; TreeNode* now = root; while(1) { while(now->left != NULL || now->right != NULL)// 找出下一个节点 { stack[top++] = now; // 当前节点入栈 if(now->left != NULL) { now = now->left; stack[top-1]->left = NULL;// 删除父亲节点的左儿子 } else { now = now->right; stack[top-1]->right = NULL;// 删除父亲节点的右儿子 } } result[all++] = now->value; if(top == 0) break; now = stack[--top]; }}int main(){/* 0 / 1 5 /\ 2 3 6 / 4*//* TreeNode* t6 = new TreeNode(6, NULL, NULL); TreeNode* t5 = new TreeNode(5, NULL, t6); TreeNode* t4 = new TreeNode(4, NULL, NULL); TreeNode* t3 = new TreeNode(3, t4, NULL); TreeNode* t2 = new TreeNode(2, NULL, NULL); TreeNode* t1 = new TreeNode(1, t2, t3); TreeNode* t0 = new TreeNode(0, t1, t5); preorderTraversal(t0, result); for(int i = 0; i < all; i++) printf("%d ", result[i]); printf("\n"); inorderTraversal(t0, result); for(int i = 0; i < all; i++) printf("%d ", result[i]); printf("\n"); postorderTraversal(t0, result); for(int i = 0; i < all; i++) printf("%d ", result[i]); printf("\n");*/ return 0;}
二叉树遍历 非递归算法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。