package com.whyc.dto.binaryTree;
|
|
import java.lang.reflect.InvocationTargetException;
|
import java.lang.reflect.Method;
|
|
/**
|
* 二叉树
|
*/
|
public class BinaryTree {
|
|
TreeNode root =null;
|
|
public BinaryTree() {
|
this.root = new TreeNode(0,"A");
|
}
|
|
public BinaryTree(TreeNode root) {
|
this.root = root;
|
}
|
|
@Override
|
public String toString() {
|
return "BinaryTree{" +
|
"root=" + root +
|
'}';
|
}
|
|
/**
|
* 创建二叉树,手动传统
|
*/
|
public BinaryTree createBinaryTree(){
|
TreeNode nodeB = new TreeNode(2, "B");
|
TreeNode nodeC = new TreeNode(3, "C");
|
TreeNode nodeD = new TreeNode(4, "D");
|
TreeNode nodeE = new TreeNode(5, "E");
|
TreeNode nodeF = new TreeNode(6, "F");
|
|
root.leftChild = nodeB;
|
root.rightChild = nodeC;
|
|
nodeB.leftChild = nodeD;
|
nodeB.rightChild =nodeF;
|
|
BinaryTree binaryTree = new BinaryTree(root);
|
return binaryTree;
|
|
}
|
|
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
|
Class<BinaryTree> binaryTreeClass = BinaryTree.class;
|
Method method = binaryTreeClass.getDeclaredMethod("createBinaryTree");
|
BinaryTree root = (BinaryTree) method.invoke(binaryTreeClass.newInstance());
|
|
|
|
}
|
|
class TreeNode{
|
private int index;
|
private String data;
|
private TreeNode leftChild;
|
private TreeNode rightChild;
|
|
public TreeNode(int index, String data) {
|
this.index = index;
|
this.data = data;
|
}
|
|
public int getIndex() {
|
return index;
|
}
|
|
public void setIndex(int index) {
|
this.index = index;
|
}
|
|
public String getData() {
|
return data;
|
}
|
|
public void setData(String data) {
|
this.data = data;
|
}
|
|
public TreeNode getLeftChild() {
|
return leftChild;
|
}
|
|
public void setLeftChild(TreeNode leftChild) {
|
this.leftChild = leftChild;
|
}
|
|
public TreeNode getRightChild() {
|
return rightChild;
|
}
|
|
public void setRightChild(TreeNode rightChild) {
|
this.rightChild = rightChild;
|
}
|
|
@Override
|
public String toString() {
|
return "TreeNode{" +
|
"index=" + index +
|
", data='" + data + '\'' +
|
", leftChild=" + leftChild +
|
", rightChild=" + rightChild +
|
'}';
|
}
|
}
|
|
|
}
|