二叉搜索 二叉完全 AVL

3 篇文章 0 订阅

二叉搜索树:
二叉搜索树左子节点的值小于父节点,右子节点的值大于父节点
中序遍历的结果就是数组排序的结果
二叉完全树:
满足 节点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就可以实现

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值