只有先序遍历部分的源代码:https://github.com/cr19941016/preOrderTree
实现环境:ubuntu16.04 + cmake3.5.1
先序遍历递归的本质就是循环和栈
void TreeHandler::myPreOrder(TreeNode* root){ // 非递归先序遍历二叉树git
cout << "mypre: ";
if(!root)
return;
stack<TreeNode*> stk;
stk.push(root);
while(!stk.empty()){
TreeNode* p = stk.top();
cout << p->data << " ";
stk.pop();
if(p->rightchild){
stk.push(p->rightchild);
}
if(p->leftchild){
stk.push(p->leftchild);
}
}
cout << endl;
}
中序遍历:
void TreeHandler::myMidOrder(TreeNode* root){
cout << "mymid: ";
stack<TreeNode*> stk;
TreeNode* p = root;
while(p || !stk.empty()){
while(p){
stk.push(p);
p = p->leftchild;
}
if(!stk.emp