二叉树

2022-03-21  本文已影响0人  请叫我平爷

Node节点

public class Node {
    int data;   //节点数据
    Node left; //左子节点
    Node right; //右子节点
    public Node(int data){
        this.data = data;
    }
}

实现
BinaryTree

package com.example.demo.day07.binary;

import com.example.demo.day07.binary.Node;
import com.example.demo.day07.binary.Tree;

public class BinaryTreeNode implements Tree {
    
    private Node root;

    @Override
    public Node find(int key) {
        Node current = root;
        while (current!=null){
            if (current.data>key){
                current = current.left;
            }
            else if (current.data<key){
                current=current.right;
            }
            else {
                return current;
            }
        }
        return null;
    }

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

}

上一篇下一篇

猜你喜欢

热点阅读