1 // Tree node defines 2 typedef struct tnode3 {4 int value; 5 tnode * left; 6 tnode * right; 7} * ptnode;
1. Non-Recursive Implementation of forward traversal (based on Recursive ideas)
Thoughts:
- When a node is accessed, it is first put into the stack, assuming that the inbound node is P.
- Access P and add the right and left children of P to the stack in sequence. This ensures that each time the left child is accessed in front of the right child.
1 void preOrderNoneRecursion(PTNode root) 2 { 3 if(root == NULL) 4 return; 5 PTNode p = root; 6 stack<PTNode> nodeStack; 7 nodeStack.push(p); 8 while(!nodeStack.empty()) 9 {10 p = nodeStack.top();11 nodeStack.pop();12 cout << p->value;13 if(p->right != NULL)14 nodeStack.push(p->right);15 if(p->left != NULL)16 nodeStack.push(p->left);17 }18 }
2. Non-Recursive Implementation of sequential traversal (based on Recursive ideas)
// You have not come up with the idea of "learning from Recursive Implementation-non-Recursive Implementation of sequential traversal"
3. Non-Recursive Implementation of post-order traversal (based on Recursive ideas)
Thoughts:
- When a node is accessed, it is first put into the stack, assuming that the inbound node is P.
- If P has no left or right children, P is directly accessed; or P has left or right children, but P's left and right children have been accessed, then directly access p.
- If the preceding two conditions are not met, P's right child and left child are added to the stack in sequence, which ensures that each time the left child is accessed in front of the right child, both the left and right children are accessed in front of the root node.
1 void postOrderNoneRecursion(PTNode root) 2 { 3 if(root == NULL) 4 return; 5 PTNode p = root; 6 PTNode pre = NULL; 7 stack<PTNode> nodeStack; 8 nodeStack.push(p); 9 while(!nodeStack.empty())10 {11 p = nodeStack.top()12 13 if( (p->left == NULL && p->right == NULL) 14 || ((pre! == NULL) && (pre == p->left || pre == p->right))15 {16 cout << p->value;17 nodeStack.pop();18 pre = p;19 }20 else21 {22 if(p->right != NULL)23 nodeStack.push(p->right);24 if(p->left != NULL)25 nodeStack.push(p->left);26 }27 }28 }
See the article:
Http://www.cnblogs.com/dolphin0520/archive/2011/08/25/2153720.html
Http://blog.csdn.net/sjf0115/article/details/8645991
Non-recursive traversal of Binary Trees (using recursive ideas for non-recursive traversal)