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



