Recursive algorithm
void Preorder1 (Node *root)//recursive pre-order traversal {if (root = NULL) return;printf ("%d", Root->val);p reorder1 (root->left); Preorder1 (root->right);} void Inorder1 (Node *root)//recursive middle order traversal {if (root = NULL) return;inorder1 (root->left);p rintf ("%d", root->val); Inorder1 (root->right);} void Postorder1 (Node *root)//recursive sequential traversal {if (root = NULL) return;postorder1 (root->left);p ostorder1 (root->right); printf ("%d", root->val);}
Stack simulation non-recursive algorithm. The recursive algorithm essentially uses the compiler to implement the stack operation.
void Preorder2 (Node *root)//non-recursive pre-order traversal {if (root = NULL) Return;stack<node *> Stk;stk.push (root); while (!stk.empty () {Node *p = Stk.top (); Stk.pop ();p rintf ("%d", p->val), if (p->right) Stk.push (p->right); if (P->left) Stk.push (P->left);}}
void Postorder2 (Node *root)//Non-recursive post-traversal, using two stacks {if (root = NULL) return;stack<node *> Stk, Stk2;stk.push (root); while ( !stk.empty ()) {Node *p = Stk.top (); Stk.pop (); Stk2.push (P); if (p->left) Stk.push (p->left); if (p->right) Stk.push (p->right);} while (!stk2.empty ()) {printf ("%d", Stk2.top ()->val); Stk2.pop ();}}
void Inorder2 (Node *root)//non-recursive middle sequence traversal {stack<node *> Stk; Node *p = Root;while (P! = NULL | |!stk.empty ()) {if (P! = null) Stk.push (p), p = p->left;else{p = Stk.top (); Stk.pop ();p rintf ("%d", p->val);p = P->right;}}}
The hierarchical traversal, which is the traversal from the top down, utilizes a queue.
void Uptodown (Node *root) {if (root = = NULL) return;queue<node *> Q; Q.push (Root) while (! Q.empty ()) {Node *p = Q.front ();p rintf ("%d", p->value); Q.pop (); Q.push (P->left); Q.push (P->right);}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Binary tree Traversal (recursive, non-recursive, hierarchical traversal (top down))