二叉树
思路
判断是否能通过一次遍历出结果。
一次遍历出结果的用构造方法 void traverse(TreeNode root)+全局变量
不能一次遍历就得考虑递归,递归就必须注意返回值
一次遍历
int x;//全局变量
public void traverse(TreeNode root){
if(root==null) return;
//前序遍历逻辑,从上往下
traverse(root.left);
traverse(root.right);
//后序遍历逻辑,从下往上
}
递归
public 返回类型 f(TreeNode,..){
if(root==null) return 0;
//逻辑
left=..;
right=..;
return ..
}
具体实现:
构造二叉树
public TreeNode f(TreeNode root){
if(..) return null;
TreeNode root=new TreeNode(..);
root.left=f();
root.right=f();
return root;
}
计算二叉树直径
public int depth(TreeNode node) {
if (node == null) {
return 0;
}
int L = depth(node.left);
int R = depth(node.right);
ans = Math.max(ans, L+R);
return Math.max(L, R) + 1;
}
二叉搜索树
遍历
二叉搜索树中序遍历是递增的
//递增
public void f(TreeNode root){
f(root.left);
f(root.right);
}
//递减
public void f(TreeNode root){
f(root.right);
f(root.left);
}
查找(可以解决增删问题)
void BST(TreeNode root, int target) {
if (root.val == target)
// 找到目标,做点什么
if (root.val < target)
BST(root.right, target);
if (root.val > target)
BST(root.left, target);
}
构造
public TreeNode f(TreeNode root,int l,int r){
if(..) return null;
TreeNode root=new TreeNode(..);
root.left=f(root,l,cur-1);
root.right=f(root,cur+1,r);
return root;
}