树结构的定义:
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
前序遍历:
递归:
class Solution {
public:
vector<int> res;
vector<int> preorderTraversal(TreeNode* root)
{
GetAns(root);
return res;
}
void GetAns(TreeNode* root)
{
if(root == NULL)
return;
res.push_back(root ->val);
GetAns(root ->left);
GetAns(root ->right);
}
};
迭代:
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root)
{
vector<int> res;
if(root == NULL)
return res;
stack<TreeNode*> s;
TreeNode *cur = root;
while(!s.empty() || cur)
{
if(cur != NULL)
{
res.push_back(cur ->val);
if(cur ->right != NULL)
s.push(cur ->right);
cur = cur ->left;
}
else
{
cur = s.top();
s.pop();
}
}
return res;
}
};
中序遍历:
递归:
class Solution {
public:
vector<int> res;
vector<int> inorderTraversal(TreeNode* root)
{
if(root == NULL)
return res;
if(root ->left != NULL)
{
inorderTraversal(root ->left);
}
res.push_back(root ->val);
if(root ->right != NULL)
{
inorderTraversal(root ->right);
}
return res;
}
};
迭代:
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root)
{
vector<int> res;
stack<TreeNode*> s;
TreeNode *cur = root;
while(!s.empty() || cur != NULL)
{
if(cur != NULL)
{
s.push(cur);
cur = cur ->left;
}
else
{
cur = s.top();
s.pop();
res.push_back(cur ->val);
cur = cur ->right;
}
}
return res;
}
};
后续遍历(迭代比起前两个较难):
递归:
class Solution {
public:
vector<int> res;
vector<int> postorderTraversal(TreeNode* root) {
if(root == NULL)
return res;
postorderTraversal(root ->left);
postorderTraversal(root ->right);
res.push_back(root ->val);
return res;
}
};
方法一:
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> s;
s.push(root);
vector<int> res;
if(root == NULL)
return res;
while(!s.empty())
{
TreeNode* temp = s.top();
if(temp->left)
{
s.push(temp->left);
temp->left = NULL;
}
else if(temp->right)
{
s.push(temp->right);
temp->right = NULL;
}
else
{
res.push_back(temp->val);
s.pop();
}
}
return res;
}
};
方法二:
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
if(root == NULL)
return res;
stack<TreeNode *> s;
s.push(root);
while(!s.empty())
{
TreeNode* node = s.top();
s.pop();
res.push_back(node ->val);
if(node ->left)
s.push(node ->left);
if(node ->right)
s.push(node ->right);
}
return vector<int>(res.rbegin(), res.rend());
}
};