void preOrderRecursive(TreeNode* tree){//前序递归算法
if(tree==null)
return;
visit(tree->value);
preOrderRecursive(tree->left);
preOrderRecursive(tree->right);
}
void preOrderNoRecursive(TreeNode* tree){//前序的非递归算法
stack<TreeNode*> s;
s.push(tree);
while(!s.empty()){
TreeNode *node=s.pop();
visit(node);
if(node->right!=null)s.push(node->right);
if(node->left!=null)s.push(node->left);
}
}
void inOrderNoRecursive(TreeNode* tree){//中序遍历的非递归算法 fucking puzzling
stack<TreeNode*> s;
TreeNode* current=tree;
while(!s.empty()||current!=null){
if(current!=null)
{
s.push(current);
current=current->left;
}else{
current=s.pop();
visit(current);
current=current->right;
}
}
}
void postOrderNoRecursive(TreeNode* tree){//后序遍历的非递归算法
stack<TreeNode*> sTraverse,sVisit;
sTraverse.push(Tree);
while(!sTraverse.empty()){
TreeNode* node=sTraverse.pop();
sVisit.push(node);
if(node->left!=null)sTraverse.push(node->left);
if(node->right!=null)sTraverse.push(node->right);
}
while(!sVisit.empty()){
visit(sVisit.pop);
}
}
树的前、中、后遍历非递归算法
最新推荐文章于 2022-12-09 18:31:27 发布