码迷,mamicode.com
首页 > 编程语言 > 详细

Java 平衡二叉树 实现

时间:2019-03-05 11:18:20      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:位置   tno   ===   nbsp   实体类   json   ice   slow   最大   

记录一下某次使用平衡二叉树。

注:二叉树概念

1、二叉树、完全二叉树、满二叉树、平衡二叉树区别

二叉树: 除了叶子节点外,每个节点只有两个分支,左子树和右子树,每个节点的最大度数为2

满二叉树:除了叶结点外每一个结点都有左右子叶 叶结点都处在最底层的二叉树。

完全二叉树:只有最下面的两层结点度小于2,并且最下面一层的结点都集中再该层最左边的若干位置的二叉树

-- 满二叉树一定是完全二叉树,完全二叉树不一定是满二叉树

平衡二叉树(AVL树):树的左右子树的高度差不超过1的数,空树也是平衡二叉树的一种。

 

一、首先要有两个实体类:

ListNode.java 链表树类

package test;

public class ListNode {
    Object val;
    ListNode next;
    ListNode(Object x) { val = x; }
}

 

TreeNode.java 二叉树类

package test;

public class TreeNode {
    Object val;
    TreeNode left;
    TreeNode right;
    TreeNode(Object x) { val = x; }
}

 

二、TreeNodeTest.java 测试类 int 数据类型

package test;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class TreeNodeTest {
    
    TreeNode treeNode =  null;
    
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        new TreeNodeTest().test();
    }
    
    public void test() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
        System.out.println("================begin :"+sdf.format(new Date()));
        
        List list = new ArrayList();
        for(int i = 1 ; i< 10; i++) {
            list.add( 3*i );
        }
        System.out.println("=======add 10000 list :"+sdf.format(new Date())+" | value :"+ list);
        
        Collections.sort(list);
        System.out.println("Collections.sort list :"+sdf.format(new Date())+" | value :"+ list);
         
        ListNode head = new ListNode(list.get(0));
        for(int i = 1; i < list.size(); i++) {
            addTreeNode(head, new ListNode(list.get(i)));
        }
        System.out.println("arraylist to ListNode :"+sdf.format(new Date()) );
        
        treeNode = sortedListToBST(head);
        System.out.println("======sortedListToBST :"+sdf.format(new Date()) );
    
        Object object = selectTreeNode(treeNode, 11);
        System.out.println("=======selectTreeNode :"+sdf.format(new Date())+" | return object val:"+object);
        
        clearTreeNode(treeNode);
        System.out.println("======sortedListToBST :"+sdf.format(new Date()) );
    }
    
    // list 按照设定字段排序
    public void sortList(List<Map<String, String>> list, String name) {
        Collections.sort(list, new Comparator<Map<String, String>>() {
            public int compare(Map<String, String> o1, Map<String, String> o2) {
                return (o1.get(name)).compareTo(o2.get(name));
            }
        });
    }
    
    // ListNode 转 TreeNode
    public TreeNode sortedListToBST(ListNode head)
    {
        if (null == head) return null;
        if (null == head.next)
        {
            return new TreeNode(head.val);
        }
        ListNode slow = head, fast = head.next.next;
        while (fast != null && fast.next != null)
        {
            fast = fast.next.next;
            slow = slow.next;
        }
        TreeNode node = new TreeNode(slow.next.val);
        node.right = sortedListToBST(slow.next.next);
        slow.next = null;
        node.left = sortedListToBST(head);
        return node;
    }
    
    // add listNode
    public ListNode addTreeNode(ListNode h1, ListNode h2)
    {
        if(h1.next == null) {
            h1.next = h2;
            return h1;
        }
        addTreeNode(h1.next, h2);
        return h1;
    }
    
    // 传入要查询的数据和对应要查询的二叉树
    public Object selectTreeNode(TreeNode node, int val) {
        
        if(Integer.parseInt(node.val.toString()) == val) {
            return node.val;
        }
        
        if(node.left == null && node.right == null) {
            if(Integer.parseInt(node.val.toString()) < val) {
                return node.val;
            }
            if(Integer.parseInt(node.val.toString()) > val) {
                return null;
            }
        }
        
        if(Integer.parseInt(node.val.toString()) > val && node.left != null) {
            return selectTreeNode(node.left, val);
        }
        
        if(Integer.parseInt(node.val.toString()) < val && node.right != null) {
            Object b = selectTreeNode(node.right, val);
            if(b == null) {
                return node.val;
            } else {
                return b;
            }
        }
        
        if(Integer.parseInt(node.val.toString()) > val) {
            return null;
        }
        
        return node.val;
    }
    
    // 销毁 TreeNode
    public void clearTreeNode(TreeNode node) {
        if(node != null) {
            if(node.left != null) clearTreeNode(node.left);
            if(node.right != null) clearTreeNode(node.right);
            node.val = null;
            node.left = null;
            node.right = null;
        }
    }
 
}

 

三、TreeNodeTest.java 测试类 list-map 数据类型

 

package test;

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;

public class TreeNodeTest {
    
    TreeNode treeNode =  null;
    Map<String, String> map = null;
    String str = "{ \"code\": 200, \"success\": true, \"message\": \"操作成功!\", \"data\": [   { \"dateTime\": \"1547438663507\",     \"deviceType\": \"4010304020302#溢满传感器\",     \"collectionTime\": \"1547437663507\",     \"mnc\": \"\",     \"dataType\": \"3\",     \"latitude\": \"\",     \"messageId\": \"\",     \"body\": \"{\\\"deviceType\\\":\\\"HLFWT\\\",\\\"waitQueue\\\":0,\\\"msgType\\\":3,\\\"alarm\\\":\\\"NORMAL\\\",\\\"deviceId\\\":\\\"00000001\\\",\\\"version\\\":\\\"V0.0.1\\\"}\",     \"cellid\": \"\",     \"productKey\": \"3eERaSscrDe\",     \"deviceId\": \"0000000001\",     \"version\": \"\",     \"lac\": \"\",     \"onLine\": \"1\",     \"dataTypeStr\": \"3\",     \"alarm\": \"\",     \"simNum\": \"\",     \"devTypeStr\": \"3eERaSscrDe\",     \"sn\": \"\",     \"devidStr\": \"0000000001\",     \"curMapType\": \"-1\",     \"direction\": \"\",     \"longitude\": \"\"   },   {     \"dateTime\": \"1547437692803\",     \"deviceType\": \"4010304020302#溢满传感器\",     \"collectionTime\": \"1547437692803\",     \"mnc\": \"\",     \"dataType\": \"3\",     \"latitude\": \"\",     \"messageId\": \"\",     \"body\": \"{\\\"deviceType\\\":\\\"HLFWT\\\",\\\"waitQueue\\\":0,\\\"msgType\\\":3,\\\"alarm\\\":\\\"NORMAL\\\",\\\"deviceId\\\":\\\"00000001\\\",\\\"version\\\":\\\"V0.0.1\\\"}\",     \"cellid\": \"\",     \"productKey\": \"3eERaSscrDe\",     \"deviceId\": \"0000000001\",     \"version\": \"\",     \"lac\": \"\",     \"onLine\": \"1\",     \"dataTypeStr\": \"3\",     \"alarm\": \"\",     \"simNum\": \"\",     \"devTypeStr\": \"3eERaSscrDe\",     \"sn\": \"\",     \"devidStr\": \"0000000001\",     \"curMapType\": \"-1\",     \"direction\": \"\",     \"longitude\": \"\"   }]   }";
    
    
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        new TreeNodeTest().test();
    }
    
    public void test() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
        
        Map maps = (Map)JSON.parse(str);  
        
        List<Map<String, String>> list =  (List<Map<String, String>>) maps.get("data");
        System.out.println("data to list : "+list);
        
        sortList(list, "dateTime");
        System.out.println("data to list sort : "+list);
        
        ListNode head = new ListNode(list.get(0));
        for(int i = 1; i < list.size(); i++) {
            addTreeNode(head, new ListNode(list.get(i)));
        }
        System.out.println("arraylist to ListNode :"+sdf.format(new Date()));
        treeNode = sortedListToBST(head);
        System.out.println("======sortedListToBST :"+sdf.format(new Date()));
    
        Object object = selectTreeNode(treeNode, 1547437763517l);
        System.out.println("========selectTreeNode:"+sdf.format(new Date())+" | return object val:"+object);
        
        clearTreeNode(treeNode);
        System.out.println("======sortedListToBST :"+sdf.format(new Date()));
    }
    
    // list 按照设定字段排序
    public void sortList(List<Map<String, String>> list, String name) {
        Collections.sort(list, new Comparator<Map<String, String>>() {
            public int compare(Map<String, String> o1, Map<String, String> o2) {
                return (o1.get(name)).compareTo(o2.get(name));
            }
        });
    }
    
    // ListNode 转 TreeNode
    public TreeNode sortedListToBST(ListNode head)
    {
        if (null == head) return null;
        if (null == head.next)
        {
            return new TreeNode(head.val);
        }
        ListNode slow = head, fast = head.next.next;
        while (fast != null && fast.next != null)
        {
            fast = fast.next.next;
            slow = slow.next;
        }
        TreeNode node = new TreeNode(slow.next.val);
        node.right = sortedListToBST(slow.next.next);
        slow.next = null;
        node.left = sortedListToBST(head);
        return node;
    }
    
    // add listNode
    public ListNode addTreeNode(ListNode h1, ListNode h2)
    {
        if(h1.next == null) {
            h1.next = h2;
            return h1;
        }
        addTreeNode(h1.next, h2);
        return h1;
    }
    
    // 传入要查询的数据和对应要查询的二叉树  , 返回二叉树对应结点值
    public Object selectTreeNode(TreeNode node, long val) {
        map = (Map<String, String>) node.val;
        
        if(val == Long.parseLong(map.get("dateTime").toString())) {
            return node.val;
        }
        
        if(node.left == null && node.right == null) {
            if(Long.parseLong(map.get("dateTime").toString()) < val) {
                return node.val;
            }
            if(Long.parseLong(map.get("dateTime").toString()) > val) {
                return null;
            }
        }
        
        if(Long.parseLong(map.get("dateTime").toString()) > val && node.left != null) {
            return selectTreeNode(node.left, val);
        }
        
        if(Long.parseLong(map.get("dateTime").toString()) < val && node.right != null) {
            Object b = selectTreeNode(node.right, val);
            if(b == null) {
                return node.val;
            } else {
                return b;
            }
        }
        
        if(Long.parseLong(map.get("dateTime").toString()) > val) {
            return null;
        }
        
        return node.val;
    }
    
    // 销毁 TreeNode
    public void clearTreeNode(TreeNode node) {
        if(node != null) {
            if(node.left != null) clearTreeNode(node.left);
            if(node.right != null) clearTreeNode(node.right);
            node.val = null;
            node.left = null;
            node.right = null;
        }
    }
 
}

 

Java 平衡二叉树 实现

标签:位置   tno   ===   nbsp   实体类   json   ice   slow   最大   

原文地址:https://www.cnblogs.com/wgy1/p/10475197.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!