# 二叉树的遍历

/**
* Definition for a binary tree node.
* 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<TreeNode*>p;
vector<int>v;
TreeNode *x = root;
while (x != NULL || p.size() != 0)
{
v.push_back(x->val);
if (x->right != NULL)
p.push_back(x->right);
x = x->left;
if (x == NULL&&p.size())
{
x = p.back();
p.pop_back();
}
}
return v;
}
};

/**
* Definition for a binary tree node.
* 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<TreeNode*>p;
vector<int>v;
if (root == NULL) return v;
TreeNode *x = root;
while (x != NULL || p.size() != 0)
{
if (x != NULL)
{
p.push_back(x);
x = x->left;
}
else
{
x = p.back(), p.pop_back();
v.push_back(x->val);
x = x->right;
}
}
return v;
}
};

/**
* Definition for a binary tree node.
* 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<TreeNode*>p;
vector<int>v;
if (root == NULL) return v;
TreeNode *x = root, *pre;
do
{
while (x != NULL) /*先遍历根节点的左子树*/
{
p.push_back(x);
x = x->left;
}
pre = NULL;
while (p.size())
{
x = p.back(), p.pop_back();
if (x->right == pre)  /*pre为上一个访问的节点，如果当前节点的右字数已经访问过，则访问根节点并更新pre*/
pre = x,v.push_back(x->val);
else  /*否则访问右子树*/
{
p.push_back(x);
x = x->right;
break;
}
}
} while (p.size());
return v;
}
};

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root)
{
queue<TreeNode*>q;
vector<vector<int> >ans;
vector<int>v;
if (root == NULL) return ans;
TreeNode *x = root;
int rev = 1; /*当前层节点的个数*/
q.push(x);
while (!q.empty())
{
x = q.front(), q.pop(), rev--;
v.push_back(x->val);
if (x->left != NULL)
q.push(x->left);
if (x->right != NULL)
q.push(x->right);
if (rev == 0)  /*判断当前一层是否已经全部访问，如果全部访问，记录数据并访问下一层*/
{
rev = q.size();
ans.push_back(v);
v.clear();
}
}
return ans;
}
};

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120