一、相关知识
可参考二叉树的基本操作(C++实现)_二叉树c++实现-CSDN博客
1、二叉树的结构
// 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) {}
* };
2、三种遍历
- 先序遍历:根左右
- 中序遍历:左根右
- 后序便伦理:左右根
3、特殊二叉树
- 满二叉树
- 完全二叉树
二、递归遍历
先序
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
if(root){
vector<int> res_left =preorderTraversal(root->left);
vector<int> res_right =preorderTraversal(root->right);
result.push_back(root->val);
for(vector<int>::iterator it = res_left.begin(); it!= res_left.end(); it++ )
result.push_back(*it);
for(vector<int>::iterator it = res_right.begin();it!=res_right.end();it++)
result.push_back(*it);
}
return result;
}
};
中序
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
if(root){
vector<int> res_left = inorderTraversal(root->left);
for(vector<int>::iterator it = res_left.begin(); it!= res_left.end(); it++ )
result.push_back(*it);
result.push_back(root->val);
vector<int> res_right = inorderTraversal(root->right);
for(vector<int>::iterator it = res_right.begin();it!=res_right.end();it++)
result.push_back(*it);
}
return result;
}
};
后序
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int>result;
if(root){
vector<int> res_left = postorderTraversal(root->left);
vector<int> res_right = postorderTraversal(root->right);
for(vector<int>::iterator it = res_left.begin(); it!=res_left.end();it++)
result.push_back(*it);
for(vector<int>::iterator it = res_right.begin();it!=res_right.end();it++)
result.push_back(*it);
result.push_back(root->val);
}
return result;
}
};
三、迭代遍历
先序:遍历过程使用栈模拟。一次迭代:先让根节点入栈,然后出栈并将值保存至结果;再依次入栈右子树和左子树(先进后出)
注意,在入栈前需要先检验是否为空
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> st;
if(root==NULL) return result;
st.push(root);
while(!st.empty()){
TreeNode* node = st.top();
st.pop();
result.push_back(node->val);
if(node->right) st.push(node->right);
if(node->left) st.push(node->left);
}
return result;
}
};
中序
迭代过程:
- 若存在左子树,则不断进入左子树,并将左子树的根节点入栈
- 若不存在左子树,则取出根节点存入结果,并进入右子树
每次迭代只有一次入栈操作:因为对于一棵子树来说,其中的每个结点都可以看作本身或某棵左子树的根节点。
同样,每次迭代也只有一次访问和存入结果的操作,因为每个结点都可以看作某棵子树的根节点
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> st;
TreeNode* node = root;
if(root==NULL) return result;
while(!st.empty()||node){
if(node){
st.push(node);
node = node->left;
}
else{
node = st.top();
result.push_back(node->val);
st.pop();
node = node->right;
}
}
return result;
}
};