Leetcode——二叉树的前序(第144题)、中序(94)、后序(145)、层序遍历(102)的递归和迭代写法总结
二叉树定义
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/*
1. 给定一个二叉树,返回它的 前序 遍历。
递归写法:
class Solution {
public:
vector<int> res;
vector<int> preorderTraversal(TreeNode* root) {
if(nullptr==root) return res;
res.push_back(root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
return res;
}
};
迭代(用stack)写法:
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(nullptr==root) return res;
stack<TreeNode*> stk;
stk.push(root);
while(!stk.empty()){
TreeNode* curr = stk.top();
res.push_back(curr->val);
stk.pop();
if(nullptr!=curr->right) stk.push(curr->right);
if(nullptr!=curr->left) stk.push(curr->left);
}
return res;
}
};
2. 给定一个二叉树,返回它的 中序 遍历。
递归写法:
class Solution {
public:
vector<int> res;
vector<int> inorderTraversal(TreeNode* root) {
if(nullptr==root) return res;
if(nullptr!=root->left) inorderTraversal(root->left);
res.push_back(root->val);
if(nullptr!=root->right) inorderTraversal(root->right);
return res;
}
};
迭代(用stack)写法:
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if(nullptr==root) return res;
stack<TreeNode*> stk;
TreeNode* curr = root;
while(!stk.empty() || nullptr!=curr){
while(nullptr!=curr){
stk.push(curr);
curr = curr->left;
}
curr=stk.top();
res.push_back(curr->val);
stk.pop();
curr = curr->right;
}
return res;
}
};
3. 给定一个二叉树,返回它的 后序 遍历。
递归写法:
class Solution {
public:
vector<int> ans;
vector<int> postorderTraversal(TreeNode* root) {
if(root==NULL) return ans;
if(root->left!=NULL) postorderTraversal(root->left);
if(root->right!=NULL) postorderTraversal(root->right);
ans.push_back(root->val);
return ans;
}
};
迭代(用stack)写法:
class Solution {
public:
// 1
// / \
// 2 3
//前序:1 2 3 =>颠倒左右访问顺序 1 3 2 =>翻转 2 3 1
//后序:2 3 1
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
if(nullptr == root) return res;
stack<TreeNode*> stk;
stk.push(root);
while(!stk.empty()){
TreeNode* curr = stk.top();
stk.pop();
res.push_back(curr->val);
if(nullptr!=curr->left) stk.push(curr->left);
if(nullptr!=curr->right) stk.push(curr->right);
}
reverse(res.begin(),res.end());
return res;
}
};
4. 给定一个二叉树,返回它的 层序 遍历。
迭代(用queue)写法:
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
if(nullptr==root) return res;
queue<pair<TreeNode*,int>> que;
que.push({root,0});
while(!que.empty()){
auto [curr,layer] = que.front();
que.pop();
if(res.size()<=layer) res.push_back({});
res[layer].push_back(curr->val);//访问每个节点的深度
if(nullptr!=curr->left) que.push({curr->left,layer+1});
if(nullptr!=curr->right) que.push({curr->right,layer+1});
}
return res;
}
};