二叉树的遍历
前序遍历
递归法代码:
class Solution {
public:
void preorder(TreeNode* root, vector<int> &ans){
if(root == nullptr){
return;
}
ans.push_back(root->val);
preorder(root->left, ans);
preorder(root->right, ans);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> ans;
preorder(root, ans);
return ans;
}
};
迭代法代码:
/**
思路:【栈】存储结点,根结点入栈、右孩子入栈、左孩子入栈
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
if(root == nullptr){
return {};
}
vector<int> ans;
stack<TreeNode*> st;
st.push(root);
while(!st.empty()){
TreeNode* cur = st.top();
st.pop();
ans.push_back(cur->val);
if(cur->right){
st.push(cur->right);
}
if(cur->left){
st.push(cur->left);
}
}
return ans;
}
};
中序遍历
递归法代码:
class Solution {
public:
void inorder(TreeNode* root, vector<int> &ans){
if(root == nullptr){
return;
}
inorder(root->left, ans);
ans.push_back(root->val);
inorder(root->right, ans);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ans;
inorder(root, ans);
return ans;
}
};
迭代法代码
1
后序遍历
递归法代码:
class Solution {
public:
void postorder(TreeNode* root, vector<int> ans){
if(root == nullptr){
return;
}
postorder(root->left, ans);
postorder(root->right, ans);
ans.push_back(root->val);
}
vector<int> postorderTraversal(TreeNode* root) {
vector<int> ans;
postorder(root, ans);
return ans;
}
};
迭代法代码
思路:后序遍历是(左右根) ,只需将先序遍历(根左右)先入栈左孩子,后入栈右孩子变成(根右左),然后对该序列再逆置,即可得 (左右根)的顺序。
/**
思路:【栈】存储结点,根结点入栈、左孩子入栈、右孩子入栈。
对遍历出来的序列求逆
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
if(root == nullptr){
return {};
}
vector<int> ans;
stack<TreeNode*> st;
st.push(root);
while(!st.empty()){
TreeNode* cur = st.top();
st.pop();
ans.push_back(cur->val);
if(cur->left){
st.push(cur->left);
}
if(cur->right){
st.push(cur->right);
}
}
reverse(ans.begin(), ans.end());
return ans;
}
};
小结
前序、中序、后序,都是开辟了一个函数,这个函数可以递归的对二叉树进行遍历。
区别:遍历 val的位置不同,前序是先放到ans中,中序是中间放入,后序是最后放入。
层序遍历
102. 二叉树的层序遍历
代码:
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
if(root == nullptr){
return {};
}
queue<TreeNode*> q;
q.push(root);
vector<vector<int>> vt;
while(!q.empty()){
int n = q.size();
vector<int> levelValues;
for(int i = 1; i <= n; i++){
TreeNode* cur = q.front();
q.pop();
levelValues.push_back(cur->val);
if(cur->left){
q.push(cur->left);
}
if(cur->right){
q.push(cur->right);
}
}
vt.push_back(levelValues);
}
return vt;
}
};