二叉搜索树:
二叉搜索树左子节点的值小于父节点,右子节点的值大于父节点
中序遍历的结果就是数组排序的结果
二叉完全树:
满足 节点i的左子节点为2*i+1 右子节点为2*i+2(如果左右都存在的话)
可以用数组存储,数组下标满足上述条件
Order(root->left)
Order(root)
Order(root-right)
借助stack,层次遍历
记得LeetCode 上之前也看到类型的
pat 1064. Complete Binary Search Tree
借助Stack 中序遍历 树的结构,然后填充层次遍历
import java.io.*;
import java.util.*;
class Node{
int val;
boolean visited;
public Node(int val,boolean vis){
this.val=val;
this.visited=vis;
}
}
public class Main{
public static void main(String args[])throws IOException{
BufferedReader buff=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(buff.readLine());
int arr[]=new int[n];
String as[]=buff.readLine().split(" ");
for(int i=0;i<n;i++)
{
arr[i]=Integer.parseInt(as[i]);
}
// search the arr
Arrays.sort(arr);
Stack<Node> stack=new Stack<Node>();
int aindex=0;
int res[]=new int[n];
int rs=0;
stack.push(new Node(0,false));
while(!stack.isEmpty()){
Node t=stack.pop();
int index=t.val;
if(t.visited){
res[index]=arr[aindex++];
}else {
if(2*index+2<n)
stack.push(new Node(2*index+2,false));
stack.push(new Node(index,true));
if(2*index+1<n)
stack.push(new Node(2*index+1,false));
}
}
for(int i=0;i<n-1;i++)
System.out.print(res[i]+" ");
System.out.println(res[n-1]);
}
}
AVL 红黑树
AVL—》
左右高度差BT(right-left)
四种情况:
RR: 节点的BT为-2 ,并且左子节点的BT为-1,做右旋转,即Node的leftnode 变为node的父节点,leftnode 的右节点变为node的左节点(顺时针)
LL : 节点的BT为+2 rightNode BT为+1 左旋转
LR:-2 +1的组合
RL:+2 -1的组合
// balance node -2 means left length longer than right and leftchild -1
// rotate the node in time
// root.left become father then root become right child beocome root's child
//LL
// node +2 node right +1
//LR
// node -2 node left +1
//RL
其他:字典序 哦哦哦 发现compareTo就可以实现