java 간단한 두 갈래 트리 구현

2436 단어
우선 node의 트리 구조를 만듭니다.
package com.assinfo.controller.tree;

public class Node {
    private  int data;
    private Node lchild;
    private Node rchild;

    public Node() {

    }

    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }

    public Node getLchild() {
        return lchild;
    }

    public void setLchild(Node lchild) {
        this.lchild = lchild;
    }

    public Node getRchild() {
        return rchild;
    }

    public void setRchild(Node rchild) {
        this.rchild = rchild;
    }

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

    @Override
    public String toString() {
        return "Node{" +
                "data=" + data +
                ", lchild=" + lchild +
                ", rchild=" + rchild +
                '}';
    }
}

두 갈래 나무를 삽입하고 훑어보기(먼저 훑어보기)
package com.assinfo.controller.tree;

import org.apache.ibatis.annotations.Insert;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Formaluetree {
    public void InsertTree(Node node, Node orign){
        if(node.getData()==0){
            orign.setData(node.getData());
        }
        if(node.getData()orign.getData()){
            if(orign.getRchild()!=null){
                InsertTree(node,orign.getRchild());
            }else{
                orign.setRchild(node);
            }
        }else{

        }
    }

    public void searchTree(Node node){
            System.out.print(node.getData()+"
"); if(node.getLchild()!=null){ searchTree(node.getLchild()); } if(node.getRchild()!=null) { searchTree(node.getRchild()); } } public static void main(String[] args) { Formaluetree binaryTree = new Formaluetree(); Node orign = new Node(); orign.setData(5); binaryTree.InsertTree(new Node(2),orign); binaryTree.InsertTree(new Node(1),orign); binaryTree.InsertTree(new Node(3),orign); binaryTree.InsertTree(new Node(4),orign); binaryTree.InsertTree(new Node(6),orign); binaryTree.InsertTree(new Node(7),orign); binaryTree.searchTree(orign); } }

좋은 웹페이지 즐겨찾기