1.中序遍历(左-中-右)
题目链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal/
方法一:递归法
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void traversal(TreeNode *cur, vector<int> &result)
{
if(cur == nullptr )
return;
traversal(cur->left, result);
result.push_back(cur->val);
traversal(cur->right, result);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
traversal(root, result);
return result;
}
};
方法二:栈-迭代法
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode * > st;
vector<int> result;
TreeNode * cur = root; //定义一个指针访问
while(cur != nullptr || !st.empty())
{
if(cur != nullptr)
{
st.push(cur);
cur = cur->left;
}else{
cur = st.top();
result.push_back(cur->val);
st.pop();
cur = cur->right;
}
}
return result;
}
};
2.前序遍历(中-左-右)
题目链接:https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
迭代法:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> result;
st.push(root);
while(!st.empty())
{
TreeNode* p = st.top();
st.pop();
if(p != nullptr) result.push_back(p->val);
else continue;
st.push(p->right); //栈先进后出
st.push(p->left);
}
return result;
}
};
3.后序遍历(左-右-中)
题目链接:https://leetcode-cn.com/problems/binary-tree-postorder-traversal/
迭代法:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> result;
TreeNode *p;
//遍历顺序 中-右-左
st.push(root);
while(!st.empty())
{
p = st.top();
st.pop();
if(p != nullptr) result.push_back(p->val);
else continue;
st.push(p->left); //栈先进后出
st.push(p->right);
}
//翻转成左-右-中
reverse(result.begin(), result.end());
return result;
}
};