java 二叉树实现算法

  1. package zxx.New;

  2. /**
  3.  * 二叉树算法实现
  4.  * 
  5.  * @author zhaoxin
  6.  * @version
  7.  */
  8. public class BinaryTree {
  9.     private TreeNode root;

  10.     public BinaryTree() {
  11.     }

  12.     public BinaryTree(Object[] objects) {
  13.     for (int i = 0; i < objects.length; i++) {
  14.         insert(objects[i]);
  15.     }
  16.     }

  17.     public boolean insert(Object o) {
  18.     if (root == null) {
  19.         root = new TreeNode(o);
  20.     } else {
  21.         // 位于父结点
  22.         TreeNode parent = null;
  23.         TreeNode current = root;
  24.         while (current != null) {
  25.         if (((Comparable) o).compareTo(current.element) < 0) {
  26.             parent = current;
  27.             current = current.left;
  28.         } else if (((Comparable) o).compareTo(current.element) > 0) {
  29.             parent = current;
  30.             current = current.right;
  31.         } else {
  32.             return false// 已经存在一个相同的元素
  33.         }
  34.         }

  35.         // 建立一个新的结点并加到父结点后
  36.         if (((Comparable) o).compareTo(parent.element) < 0) {
  37.         parent.left = new TreeNode(o);
  38.         } else {
  39.         parent.right = new TreeNode(o);
  40.         }
  41.     }

  42.     return true// 元素已经插入
  43.     }

  44.     public void inorder() {
  45.     inorder(root);
  46.     }

  47.     private void inorder(TreeNode root) {
  48.     if (root == null) {
  49.         return;
  50.     }

  51.     inorder(root.left);
  52.     System.out.print(root.element + " ");
  53.     inorder(root.right);
  54.     }

  55.     public void postorder() {
  56.     postorder(root);
  57.     }

  58.     private void postorder(TreeNode root) {
  59.     if (root == null) {
  60.         return;
  61.     }

  62.     postorder(root.left);
  63.     postorder(root.right);
  64.     System.out.print(root.element + " ");
  65.     }

  66.     public void preorder() {
  67.     preorder(root);
  68.     }

  69.     private void preorder(TreeNode root) {
  70.     if (root == null) {
  71.         return;
  72.     }

  73.     System.out.print(root.element + " ");
  74.     preorder(root.left);
  75.     preorder(root.right);
  76.     }

  77.     private static class TreeNode {
  78.     Object element;
  79.     TreeNode left;
  80.     TreeNode right;

  81.     public TreeNode(Object o) {
  82.         element = o;
  83.     }
  84.     }
  85. }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值