二叉树前序遍历:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> preorderTraversal(TreeNode *root) { vector<int> res; if(root==NULL)return res; stack<TreeNode *> sta; sta.push(root); while(!sta.empty()) { TreeNode *tmp=sta.top(); sta.pop(); res.push_back(tmp->val); if(tmp->right)sta.push(tmp->right); if(tmp->left)sta.push(tmp->left); } return res; } /** void preorder(vector<int> &res, TreeNode * root) { if(root==NULL)return; res.push_back(root->val); preorder(res,root->left); preorder(res,root->right); } vector<int> preorderTraversal(TreeNode *root) { vector<int> res; preorder(res,root); return res; } */ };
二叉树中序遍历:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> inorderTraversal(TreeNode *root) { vector<int> res; if(root==NULL)return res; TreeNode *p=root; stack<TreeNode *> sta; while(p!=NULL||!sta.empty()) { while(p!=NULL) { sta.push(p); p=p->left; } if(!sta.empty()) { p=sta.top(); sta.pop(); res.push_back(p->val); p=p->right; } } return res; } /* void inorder(TreeNode *root, vector<int> &res) { if(root==NULL)return; inorder(root->left,res); res.push_back(root->val); inorder(root->right,res); return; } vector<int> inorderTraversal(TreeNode *root) { vector<int> res; inorder(root,res); return res; } */ };
二叉树后序遍历:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> postorderTraversal(TreeNode *root) { vector<int> res; if(root==NULL)return res; map<TreeNode *, int> smap; smap[root]=0; stack<TreeNode *> sta; sta.push(root); while(!sta.empty()) { TreeNode *p=sta.top(); if((!p->right&&!p->left)||smap.count(p->right)||smap.count(p->left)) { res.push_back(p->val); smap[p]=1; sta.pop(); } else { if(p->right&&!smap.count(p->right)) { sta.push(p->right); smap[p->right]=0; } if(p->left&&!smap.count(p->left)) { sta.push(p->left); smap[p->left]=0; } } } return res; } /** void postorder(vector<int> & res,TreeNode *root) { if(root==NULL)return; postorder(res,root->left); postorder(res,root->right); res.push_back(root->val); } vector<int> postorderTraversal(TreeNode *root) { vector<int> res; postorder(res,root); return res; } */ };