一些性质:
1.前序遍历第一个元素是root,后序遍历最后一个元素是root,中序遍历root的左边元素是左分支,右边元素是右分支;
2.已知前中遍历,或者中后遍历可确定二叉树,前后不行;
3.二叉搜索树中序遍历有序;
4.如果t1是t2的子树,那么t1序列化的结果是t2序列化的子序列;
遍历:
1.递归前序
vector<int> res;
void preorder(Treenode* root){
if(root==NULL) return; //这里也可以对res操作,但注意要return
res.push_back(root->val);
preorder(root->left); //注意先左后右
preorder(root->right);
}
2.递归中序
vector<int> res;
void preorder(Treenode* root){
if(root==NULL) return; //这里也可以对res操作,但注意要return
preorder(root->left); //注意先左后右
res.push_back(root->val);
preorder(root->right);
}
3.递归后序
vector<int> res;
void preorder(Treenode* root){
if(root==NULL) return; //这里也可以对res操作,但注意要return
preorder(root->left); //注意先左后右
preorder(root->right);
res.push_back(root->val);
}
4.层序遍历BFS
vector<int> res;
void bfs(Treenode* root){
if(root==NULL) return res;
deque<Treenode*> q;
q.push(root);
while(!q.empty()){
int s=q.size(); //q的size在for循环中会变,注意刚开始就求
Treenode* temp;
for(int i=0;i<s;++i){
temp=q.front();
q.pop();
res.push_back(temp);
if(temp->left) q.push(temp->left); //注意先左后右
if(temp->right) q.push(temp->right);
}
}
}
5.借助栈
来自leetcode https://leetcode-cn.com/problems/binary-tree-inorder-traversal/solution/dong-hua-yan-shi-94-er-cha-shu-de-zhong-xu-bian-li/
**
应用:
**
1.求树深度
int height(Treenode* root){
if(root==NULL) return 0;
int left=height(root->left);
int right=height(root->right);
return max(left,right)+1;
}
或者用BFS每一层加一的方法
2.二叉树很多用递归的,后面再补充吧