二叉树理论基础
二叉树递归遍历
如何书写递归函数?
- 确定递归函数的参数和返回值
- 确定终止条件
- 确定单层递归的逻辑
二叉树迭代遍历
一、做题感受&第一想法
知道手算方法,但是写成代码有困难。没写出来。
二、学习文章后收获
1.中序遍历
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();
st.pop();
result.push_back(cur->val);
cur = cur->right;
}
}
return result;
}
};
2.先序遍历
最简单,因为遍历顺序和处理顺序相同。
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> st;
TreeNode* cur = NULL;
st.push(root);
while( !st.empty() ){
cur = st.top();
st.pop();
if(cur != NULL){
result.push_back(cur->val);
st.push(cur->right);
st.push(cur->left);
}
}
return result;
}
};
3.后序遍历
先序遍历是“根左右”,后序遍历是“左右根”。那么可以先按“根右左”遍历,再reverse翻转一下。
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> st;
TreeNode* cur = NULL;
st.push(root);
while( !st.empty() ){
cur = st.top();
st.pop();
if(cur != NULL){
result.push_back(cur->val);
st.push(cur->left);
st.push(cur->right);
}
}
reverse(result.begin(),result.end());
return result;
}
};
三、过程中遇到的问题
1.vector如何reverse翻转
vector没有reverse()
的成员函数!
reverse(v.begin(),v.end()); //会翻转左闭右开区间
二叉树统一迭代
题目链接:同上
文章讲解:link
一、做题感受&第一想法
没有思路。
二、学习文章后收获
主要思路:NULL标识处理元素
根节点先入栈。此后栈不为空则一直循环。
每次循环时,弹出栈顶元素:
①如果栈顶元素不为NULL,则右孩子先入栈(NULL则不入栈),然后自己入栈,然后NULL入栈,然后左孩子入栈(NULL则不入栈)。
②如果栈顶元素为NULL,则说明下一个元素是需要输出的节点,那么弹出栈顶元素,把它的val加入result容器中。
1.中序遍历
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> st;
TreeNode* cur = NULL;
if(root) st.push(root);
while(!st.empty()){
cur = st.top();
st.pop();
if(cur){ //按 右、根、左 入栈。
if(cur->right) st.push(cur->right);
st.push(cur);
st.push(NULL);
if(cur->left) st.push(cur->left);
}
else{
cur = st.top();
st.pop();
result.push_back(cur->val);
}
}
return result;
}
};
2.先序遍历
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> st;
TreeNode* cur;
if(root) st.push(root);
while(!st.empty()){
cur = st.top();
st.pop();
if(cur){ //按 右、左、根 入栈。
if(cur->right) st.push(cur->right);
if(cur->left) st.push(cur->left);
st.push(cur);
st.push(NULL);
}
else{
cur = st.top();
st.pop();
result.push_back(cur->val);
}
}
return result;
}
};
3.后序遍历
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> st;
TreeNode* cur;
if(root) st.push(root);
while(!st.empty()){
cur = st.top();
st.pop();
if(cur){ //按 根、右、左 入栈。
st.push(cur);
st.push(NULL);
if(cur->right) st.push(cur->right);
if(cur->left) st.push(cur->left);
}
else{
cur = st.top();
st.pop();
result.push_back(cur->val);
}
}
return result;
}
};