1, Binary tree node definition
typedef struct BTREENODEELEMENT_T_ { void *data;} btreenodeelement_t;typedef struct Btreenode_t_ { btreenodeelement_t *m_pelemt; struct Btreenode_t_ *m_pleft; struct btreenode_t_ *m_pright;} btreenode_t;
2. Pre-sequence traversal
Definition: First access to the root node, in the access to the left subtree, and finally access the right sub-tree;
(1) Recursive implementation
Returns if the root node is null.
If the root node is not null, the root node is accessed first, then the left subtree is accessed, and the right subtree is accessed last
void Preordertraverse (btreenode_t *proot) { if (proot = = NULL) return; Visit (proot); Preordertraverse (proot->m_pleft); Preordertraverse (proot->m_pright); return;}
(2) Non-recursive implementation
Using the STL Stack implementation
The first step: first to determine whether Proot is empty, if not empty, then take the second step, if it is empty, then the third step.
The second step: Access the Proot, then put the proot into the stack, assign the Proot left node to Proot, and then take the first step to the new proot.
The third step: Determine whether the stack is empty, if not empty, then take out the top of the stack, and out of the stack, and then assign the right node of the top of the stack to Proot, and then take the first step; if Proot is null and the stack is empty, it ends.
void Preordertraverse (btreenode_t *proot) { if (proot = = NULL) return; Stack <btreenode_t *> St; while (proot! = NULL | |!st.empty ()) { while (proot! = null) { Visit (proot); St.push (proot); Proot = proot->m_pleft; } if (!st.empty ()) { proot = St.top (); St.pop (); Proot = proot->m_pright; } } return;}
Binary tree (1)----First Order traversal (pre-order traversal), recursive and non-recursive implementations