二叉树主要有两种遍历思路,一种是深度优先搜索,一直往子叶遍历然后返回。一种是广度优先遍历,每一层每一层的逐次遍历。这就和图论是一样的。
其中深度优先搜索有前中后遍历三种方法,实现遍历的方法又有递归和迭代
怎么记住三种遍历方式呢,主要是看“中”的位置
前序遍历就是中左右
中序就是左中右
后序就是左右中
二叉树的实现我们以最常用的链式储存方法
遍历方法采取递归写法
题目链接如下:
144. 二叉树的前序遍历
class Solution {
public:
void dfs(TreeNode*cur , vector<int>&res){
if(cur == NULL)return ;
//前序,中左右
res.push_back(cur->val);
dfs(cur->left , res);
dfs(cur->right , res);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
dfs(root,res);
return res;
}
};
94. 二叉树的中序遍历
class Solution {
public:
void dfs(TreeNode*cur , vector<int>&res){
if(cur == NULL)return;
//中序,左中右
dfs(cur->left , res);
res.push_back(cur->val);
dfs(cur->right , res);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int>res;
dfs(root,res);
return res;
}
};
45. 二叉树的后序遍历
class Solution {
public:
void dfs(TreeNode*cur , vector<int>&res){
if(cur == NULL)return;
//后序,左右中
dfs(cur->left , res);
dfs(cur->right , res);
res.push_back(cur->val);
}
vector<int> postorderTraversal(TreeNode* root) {
vector<int>res;
dfs(root , res);
return res;
}
};
最后我们发现,不同的遍历顺序也就是递归的时候几行代码的顺序不同
学会写递归,记住三点就好了
确定参数和返回值
确定终止条件
确定单层递归的逻辑
迭代法则是借助栈来实现
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*>st;
vector<int>res;
if(root == NULL)return res;
st.push(root);
while(!st.empty()){
TreeNode*node = st.top();
st.pop();
res.push_back(node->val);//中
//先右后左,出去的时候就是先左后右
if(node->right)st.push(node->right);
if(node->left)st.push(node->left);
}
return res;
}
};
后序就是多一个翻转,变一点顺序
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> result;
if (root == NULL) return result;
st.push(root);
while (!st.empty()) {
TreeNode* node = st.top();
st.pop();
result.push_back(node->val);
if (node->left) st.push(node->left); // 相对于前序遍历,这更改一下入栈顺序 (空节点不入栈)
if (node->right) st.push(node->right); // 空节点不入栈
}
reverse(result.begin(), result.end()); // 将结果反转之后就是左右中的顺序了
return result;
}
};
中序遍历借助了一下指针
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> st;
TreeNode* cur = root;
while (cur != NULL || !st.empty()) {
if (cur != NULL) { // 指针来访问节点,访问到最底层
st.push(cur); // 将访问的节点放进栈
cur = cur->left; // 左
} else {
cur = st.top(); // 从栈里弹出的数据,就是要处理的数据(放进result数组里的数据)
st.pop();
result.push_back(cur->val); // 中
cur = cur->right; // 右
}
}
return result;
}
};