Java 二叉树

    xiaoxiao2021-03-25  119

    package test.er; //节点 public class Node { private Integer id;//关键字 private Integer otherData;//其他数据 private Node left;//左节点 private Node right;//右节点 public Node(Integer id, Integer otherData) { super(); this.id = id; this.otherData = otherData; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getOtherData() { return otherData; } public void setOtherData(Integer otherData) { this.otherData = otherData; } public Node getLeft() { return left; } public void setLeft(Node left) { this.left = left; } public Node getRight() { return right; } public void setRight(Node right) { this.right = right; } public void tString(){ System.out.println(this.getId()+"-"+this.getOtherData()); } } package test.er; /** * 二叉树 * @author john * */ public class Tree { private static Node root;//根节点 //插入 大的放右边 小的放左边 public static void insert(Integer key,Integer otherData){ Node node = new Node(key,otherData); if(root==null){ root = node; }else{ Node current = root; Node parent; while(true){ parent = current; if(otherData<current.getOtherData()){ current = current.getLeft(); if(current==null){ parent.setLeft(node); return; } }else{ current = current.getRight(); if(current==null){ parent.setRight(node); return; } } } } } /** * * * description:先序遍历 节点先显示 */ public static void deplaypre(Node node){ if(node!=null){ node.tString();//前 deplaypre(node.getLeft()); deplaypre(node.getRight()); } } /** * * * description:中序遍历 节点在中间显示 */ public static void deplayin(Node node){ if(node!=null){ deplayin(node.getLeft()); node.tString();//中 deplayin(node.getRight()); } } /** * * * description:后序遍历 最后显示 */ public static void deplayback(Node node){ if(node!=null){ deplayback(node.getLeft()); deplayback(node.getRight()); node.tString();//后 } } //测试 public static void main(String[] args) { insert(99, 99); insert(44, 44); insert(100, 100); insert(55, 55); insert(31, 31); insert(42, 42); insert(54, 54); deplaypre(root); } } 结果 31-31 42-42 44-44 54-54 55-55 99-99 100-100
    转载请注明原文地址: https://ju.6miu.com/read-20281.html

    最新回复(0)