树结点
- struct TreeNode {
- int val;
- struct TreeNode *left;
- struct TreeNode *right;
- TreeNode(int x):val(x),left(NULL),right(NULL){}
- };
- typedef struct TreeNode TreeNode;
访问函数
- void visit(TreeNode *root)
- {
- if(root)
- cout <<root->val<<" ";
- }
前序递归
- void preorder(TreeNode *root)
- {
- if(root)
- {
- visit(root);
- preorder(root->left);
- preorder(root->right);
- }
- }
前序非递归
- void preorder1(TreeNode *root)
- {
- stack<TreeNode*> s;
- while(root || !s.empty())
- {
- if(root)
- {
- visit(root);
- s.push(root->right);
- root = root->left;
- }
- else
- {
- root = s.top();
- s.pop();
- }
- }
- }
中序递归
- void inorder(TreeNode *root)
- {
- if(root)
- {
- inorder(root->left);
- visit(root);
- inorder(root->right);
- }
- }
中序非递归
- void inorder1(TreeNode *root)
- {
- stack<TreeNode*> s;
- while(root || !s.empty())
- {
- if(root)
- {
- s.push(root);
- root = root->left;
- }
- else
- {
- root = s.top();
- s.pop();
- visit(root);
- root = root->right;
- }
- }
- }
后序递归
- void postorder(TreeNode *root)
- {
- if(root)
- {
- postorder(root->left);
- postorder(root->right);
- visit(root);
- }
- }
后序非递归1,使用双栈
- void postorder1(TreeNode *root)
- {
- stack<TreeNode*> s1;
- stack<TreeNode*> s2;
- if(!root) return;
- s1.push(root);
- while(!s1.empty())
- {
- s2.push(s1.top());
- s1.pop();
- if(s2.top()->left)
- s1.push(s2.top()->left);
- if(s2.top()->right)
- s1.push(s2.top()->right);
- }
- while(!s2.empty())
- {
- visit(s2.top());
- s2.pop();
- }
- }
后序非递归2,使用一个pre指针
- void postorder2(TreeNode *root)
- {
- stack<TreeNode*> s;
- TreeNode *pre = NULL;
- TreeNode *cur;
- if(!root) return;
- s.push(root);
- while(!s.empty())
- {
- cur = s.top();
- if(!pre || (pre != cur->right && pre != cur->left))
- {
- if(!cur->left && !cur->right)
- {
- visit(cur);
- s.pop();
- pre = cur;
- }
- if(cur->right)
- s.push(cur->right);
- if(cur->left)
- s.push(cur->left);
- }
- else if( pre == cur->left)
- {
- if(cur->right)
- s.push(cur->right);
- else
- {
- visit(cur);
- s.pop();
- pre = cur;
- }
- }
- else if(pre == cur->right)
- {
- visit(cur);
- s.pop();
- pre = cur;
- }
- }
- }
层次遍历,使用队列
- void level_traversal(TreeNode *root)
- {
- queue<TreeNode*> q;
- if(!root) return;
- q.push(root);
- while(!q.empty())
- {
- if(q.front()->left)
- q.push(q.front()->left);
- if(q.front()->right)
- q.push(q.front()->right);
- visit(q.front());
- q.pop();
- }
- }
(更新中)
本文转自nxlhero 51CTO博客,原文链接:http://blog.51cto.com/nxlhero/1159213,如需转载请自行联系原作者