1. 递归遍历
1.1 前序遍历
vector<int> res;
vector<int> PreTravelsal(vector<int> res, TreeNode* root)
{
res.clear();
travelsal(root);
return res;
}
void travelsal(TreeNode* cur)
{
if(cur == NULL) return;
res.push_back(cur->val);
travelsal(cur->left);
travelsal(cur->right);
}
1.2 中序遍历
vector<int> res;
vector<int> PreTravelsal(vector<int> res, TreeNode* root)
{
res.clear();
travelsal(root);
return res;
}
void travelsal(TreeNode* cur)
{
if(cur == NULL) return;
res.push_back(cur->val);
//travelsal(cur->left);
res.push_back(cur->val);
travelsal(cur->right);
}
1.3 后序遍历
vector<int> res;
vector<int> PreTravelsal(vector<int> res, TreeNode* root)
{
res.clear();
travelsal(root);
return res;
}
void travelsal(TreeNode* cur)
{
if(cur == NULL) return;
//res.push_back(cur->val);
travelsal(cur->left);
travelsal(cur->right);
res.push_back(cur->val);
}
2. 迭代遍历
2.1 前序遍历
vector<int> travelsal(TreeNode* root)
{
vector<int> res;
stack<TreeNode*> st;
if(root == NULL) return res;
st.push(root);
while(!st.empty())
{
TreeNode* cur = st.top();
st.pop();
res.push_back(cur->val);
if(cur->right) st.push(cur->right);
if(cur->left) st.push(cur->left);
}
return res;
}
2.2 后序遍历
vector<int> travelsal(TreeNode* root)
{
vector<int> res;
stack<TreeNode*> st;
if(root == NULL) return res;
st.push(root);
while(!st.empty())
{
TreeNode* cur = st.top();
st.pop();
res.push_back(cur->val);
if(cur->left) st.push(cur->left);
if(cur->right) st.push(cur->right);
}
reverse(res.begin(), res.end());
return res;
}
2.3 中序遍历
vector<int> travelsal(TreeNode* root)
{
vector<int> res;
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();
res.push_back(cur->val);
cur = cur->right;
}
}
return res;
3. 层序遍历
vector<int> travelsal(TreeNode* root)
{
vector<int> res;
queue<TreeNode*> que;
if(root == NULL) return res;
que.push(root);
while(!que.empty())
{
int n = que.size();
for(int i = 0; i < n; i++)
{
TreeNode* cur = que.front();
que.pop();
res.push_back(cur->val);
if(cur->left) que.push(cur->left);
if(cur->right) que.push(cur->right);
}
}
return res;
}
4. 二叉树的种类
- 完全二叉树:一根二叉树只有度为0的结点和度为2的结点,并且度为0的结点在同一层上,其深度为k,结点数为2^k-1;
- 完全二叉树:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2^(h-1) 个节点。
- 二叉搜索树:若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值;若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;它的左、右子树也分别为二叉排序树。
4.平衡二叉搜索树:又被称为AVL(Adelson-Velsky and Landis)树,且具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。