二叉树

java实现的二叉树.

package tree;

import lombok.Data;

@Data
public class Node implements Tree {

  private Node root = this;
  private Integer data;
  private Node left;
  private Node right;
  private Boolean isDelete;

  public Node(Integer data) {
    this.data = data;
  }

  public Node() {
  }

  public Node(Integer data, Node left, Node right) {
    this.data = data;
    this.left = left;
    this.right = right;
  }

  //打印节点内容
  public void display() {
    System.out.println(data);
  }

  //遍历树--中序遍历
  public void midEach(Node node) {
    if (node == null) {
      System.out.println("空树");
    }
    if (node.left != null) {
      midEach(node.left);
    }
    System.out.print(node.data + " ");//中序遍历
    if (node.right != null) {
      midEach(node.right);
    }
  }

  //前序遍历
  public void preEach(Node node) {
    if (node == null) {
      System.out.println("空树");
    }
    System.out.print(node.data + " ");//前序遍历
    if (node.left != null) {
      preEach(node.left);
    }
    if (node.right != null) {
      preEach(node.right);
    }
  }

  //后序遍历
  public void postEach(Node node) {
    if (node == null) {
      System.out.println("空树");
    }
    if (node.left != null) {
      postEach(node.left);
    }
    if (node.right != null) {
      postEach(node.right);
    }
    System.out.print(node.data + " ");//后序遍历
  }

  @Override
  public Node find(Integer key) {
    Node current = this.root;
    while (current != null) {
      if (current.data > key) {
        current = current.left;
      } else if (current.data < key) {
        current = current.right;
      } else {
        return current;
      }
    }
    //遍历完整个树没找到,返回null.
    return null;
  }

  @Override
  public boolean insert(Integer key) {
    Node node = new Node(key);
    if (this.root == null) {
      this.root = node;
      return true;
    } else {
      Node current = root;
      Node parent;
      while (current != null) {
        parent = current;
        if (current.data > key) {
          current = current.left;
          if (current == null) {
            parent.left = node;
            return true;
          }
        } else {
          current = current.right;
          if (current == null) {
            parent.right = node;
            return true;
          }
        }
      }
    }
    return false;
  }

  @Override
  public boolean delete(Integer key) {
    //这里的删除比较复杂,可以用一个Boolean标签记录是否被删除.而不用破坏树的结构
    return false;
  }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值