JAVA - 怎么根据输入的数据建立binary tree?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVA - 怎么根据输入的数据建立binary tree?相关的知识,希望对你有一定的参考价值。
就是比如用户输入: A,B,C,D,E,F, (输入end的话就是停止输入了)
然后就建立一个Binary tree:
A
/ \
B C
/ \ /
D E F
A是root。。位置放错了
Binary Tree可以用的method有:
makeRoot(T data)
setData(T data)
setLeft(BinaryTree t)
setRight(BinaryTree t)
setParent(BinaryTree t)
getLeft()
getRight()
getParent()
attachLeft(BinaryTree t)
attachRight(BinaryTree t)
detachLeft(BinaryTree t)
detachRight(BinaryTree t)
isEmpty();
package com.chruan.tree;
public class BinaryTree <T>
private T data;
private BinaryTree right;
private BinaryTree left;
private BinaryTree parent;
public void makeRoot(T data)
this.data = data;
public T getData()
return data;
public void setData(T data)
this.data = data;
public BinaryTree getRight()
return right;
public void setRight(BinaryTree right)
this.right = right;
public BinaryTree getLeft()
return left;
public void setLeft(BinaryTree left)
this.left = left;
public BinaryTree getParent()
return parent;
public void setParent(BinaryTree parent)
this.parent = parent;
public boolean isEmpty()
return data==null;
public void attachLeft(BinaryTree t)
public void attachRight(BinaryTree t)
public void detachLeft(BinaryTree t)
public void detachRight(BinaryTree t)
package com.chruan.tree;
import java.util.Stack;
public class Main
public static void main(String[] args)
String treeStr = "A,B,C,D,E,F";
Stack<BinaryTree<String>> stackLevel = new Stack<BinaryTree<String>>();
BinaryTree<String> root = new BinaryTree<String>();
root.setData(treeStr.charAt(0)+"");
stackLevel.add(root);
int idx = 0;
BinaryTree<String> curNode=null;
int treeLen = treeStr.length();
while((curNode = stackLevel.pop())!=null && idx < treeLen)
idx +=2;
if (idx>treeLen)
break;
BinaryTree<String> left=new BinaryTree<String>();
left.setData(treeStr.charAt(idx)+"");
curNode.setLeft(left);
stackLevel.push(left);
idx +=2;
if (idx>treeLen)
break;
BinaryTree<String> right=new BinaryTree<String>();
right.setData(treeStr.charAt(idx)+"");
curNode.setRight(right);
参考技术A 设计个节点node类
class Node
public char value; //字母节点
public Node left,right;//左右子节点
完美树就从根节点root挨个填
以上是关于JAVA - 怎么根据输入的数据建立binary tree?的主要内容,如果未能解决你的问题,请参考以下文章
eclipse中Java(TM) Platform SE binary已停止工作怎么解决