前序递归于循环
#include <iostream> #include <stack> using namespace std; struct TreeNode { int val; TreeNode *left,*right; }; void create(TreeNode *&p) { int k; cin>>k; //1 2 0 0 3 0 0; if(k!=0) { p=new TreeNode; p->val=k; create(p->left); create(p->right); } else p=NULL; } void preorder1(TreeNode *p) { if(p) { cout<<p->val; preorder1(p->left); preorder1(p->right); } } void preorder2(TreeNode *root) { stack<TreeNode*> s; TreeNode *p=root; while(p||!s.empty()) { if(p) { s.push(p); cout<<p->val; p=p->left; } else { p=s.top(); s.pop(); p=p->right; } } }
中序递归与循环
void inorder1(TreeNode *p) { if(p) { inorder1(p->left); cout<<p->val; inorder1(p->right); } } void inorder2(TreeNode *p) { stack<TreeNode*> s; while(p||!s.empty()) { if(p) { s.push(p); p=p->left; } else { p=s.top(); cout<<p->val; s.pop(); p=p->right; } } } int main() { TreeNode *root=new TreeNode; create(root); //preorder1(root); preorder2(root); //inorder1(root); inorder2(root); return 0; }
时间: 2024-12-28 23:52:48