目录
一:二叉树概念总结:
1.Java实现二叉树
class TreeNode{
int val;
TreeNode left ;
TreeNode right;
TreeNode(int val){
this.val = val;
this.left = null;
this.right = null;
}
}
2.二叉树的遍历:
1)先序:根左右
2)中序:左根右
3)后序:左右根
【树的遍历用for循环相对麻烦,用递归比较方便和简洁】
3.二叉搜索树:
也称有序二叉树,排序二叉树,是指一棵空树或者具有下列性质的二叉树:
1)左子树上所有结点值均小于它的根节点的值;
2)右子树上所有结点的值均大于它的根节点的值
3)以此类推,左右子树也分别为二叉查找树
【注意1】:二叉搜索树的中序遍历是升序遍历(从小到大)
【注意2】:二查搜索树的查询和操作都是log(n)
[注意3]:有时候使用二叉树的不同遍历方式可以有效解决题目:例如右根左遍历方式等等,
不一定要局限于常用三种遍历方式。
4.二叉搜索树三种方式遍历模板
// 先序
preorder (root){
if(root!=null){
traverse_path.append(root.val);
preorder(root.left);
preorder(root.right);
}
}
// 中序
inorder(root){
if(root != null){
inorder(root.left);
traverse_path.append(root.val);
inorder(root.right);
}
}
// 后序
postorder(root){
if(root != null){
postorder(root.left);
postorder(root.right);
traverse_path(root.val);
}
}
[注意]:上面的三种遍历方式的模板必须熟练
题目一:二叉树的中序遍历
给定一个二叉树的根节点 root
,返回它的 中序 遍历。
示例 1:
输入:root = [1,null,2,3]
输出:[1,3,2]
思路:使用二叉树的中序递归模板(要熟记二叉树三种遍历的模板)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;