二叉树的遍历
1.前序遍历(根左右)
//非递归实现
//
/** leetcode 144
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*> s;
TreeNode* tmp=root;
vector<int> res;
while(!s.empty()||tmp!=NULL)
{
while(tmp)
{
s.push(tmp);
res.push_back(tmp->val);
tmp=tmp->left;
}
tmp=s.top();
s.pop();
tmp=tmp->right;
}
return res;
}
//递归实现
vector<int> res;
vector<int> preorderTraversal(TreeNode* root) {
if(root)
res.push_back(root->val);
else
return {};
if(root->left)
preorderTraversal(root->left);
if(root->right)
preorderTraversal(root->right);
return res;
}
2.中序遍历(左根右)
//参考 leetcode 145
//非递归实现,使用pre来表示,当前节点的右节点是否被访问过
vector<int> postorderTraversal(TreeNode* root){
stack<TreeNode*> s;
vector<int> res;
TreeNode* pre=NULL;
TreeNode* cur=root;
while(cur||!s.empty())
{
while(cur)
{
s.push(cur);
cur=cur->left;
}
cur=s.top();
if(!cur->right||cur->right==pre)
{
res.push_back(cur->val);
s.pop();
pre=cur;
cur=NULL;
}
else
{
cur=cur->right;
//pre=NULL;
}
}
return res;
}
/*递归实现
vector<int> res;
vector<int> postorderTraversal(TreeNode* root) {
if(!root)
return {};
if(root->left)
postorderTraversal(root->left);
if(root->right)
postorderTraversal(root->right);
res.push_back(root->val);
return res;
}
*/
3.后序遍历(左右根)
//递归实现
vector<int> res;
vector<int> inorderTraversal(TreeNode* root) {
/*
if(!root)
return {};
if(root->left)
inorderTraversal(root->left);
res.push_back(root->val);
if(root->right)
inorderTraversal(root->right);
return res;
*/
//非递归实现 leetcode 94
vector<int> res;
stack<TreeNode*> s;
TreeNode* cur=root;
while(!s.empty()||cur)
{
while(cur)
{
s.push(cur);
cur=cur->left;
}
cur=s.top();
res.push_back(cur->val);
s.pop();
cur=cur->right;
}
return res;
}
4.层序遍历
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
if(!root)
return res;
queue<TreeNode*> q;
q.push(root);
int num=1;
int coun=1;
vector<int> v;
while(!q.empty())
{
num=q.size();
v.clear();
while(num--)
{
TreeNode* tmp=q.front();
q.pop();
v.push_back(tmp->val);
if(tmp->left)
{
q.push(tmp->left);
}
if(tmp->right)
{
q.push(tmp->right);
}
}
res.push_back(v);
}
return res;
}