您的位置:首页 > 编程语言 > Java开发

java实现二叉树

2016-04-18 21:21 369 查看
用java实现实现二叉树

第一步:创建节点类

<span style="font-size:18px;">class TreeNode {
private Object nodeValue;
private TreeNode left, right;

public TreeNode(){
this(null, null, null);
}

public TreeNode(Object item){
nodeValue = item;
}

public TreeNode(Object item, TreeNode left, TreeNode right){
nodeValue = item;
this.left = left;
this.right = right;
}
//判断当前节点是否为叶子
public boolean isEmpty(){
if (this.left == null && this.left == null){
return true;
}
return false;
}
//重写toString方法
public String toString(){
if (nodeValue == null){
return null;
}

String result = "(节点" + nodeValue.toString();

if (left != null){
result += "左节点" + left.toString();
}
if (right != null){
result += "右节点" + right.toString();
}

result += ")";
return result;
}
}

//实现二叉树
class BinaryTree {
    protected TreeNode root;//定义一个节点对象成员
    
    public BinaryTree(){
        root = null;
    }
    
    public BinaryTree(TreeNode root){
        this.root = root;
    }
    
    public boolean isEmpty(){
        return this.root == null;
    }
    
    public TreeNode getRoot(){
        return root;
    }
    
    public String toString(){
        return root.toString();
    }
}

实现如图所示的二叉树
<img src="http://img.blog.csdn.net/20160418211703770?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" height="259" width="572" />
</span>


//构造二叉树

<span style="font-size:18px;">public class BulidBinaryTree {
public static BinaryTree creat(){
TreeNode a, b, c, d, e, f, g;
//创建叶子
f = new TreeNode("F");
g = new TreeNode("G");
d = new TreeNode("D");
c = new TreeNode("C");
//创建根节点
e = new TreeNode("E", f, g);
b = new TreeNode("B", d, e);
a = new TreeNode("A", b, c);

return new BinaryTree(a);
}
}
</span>


//测试并输出

<span style="font-size:18px;">public class TestDemo {
public static void main(String[] args) {
BinaryTree binaryTree = BulidBinaryTree.creat();
System.out.println(binaryTree);
}
}
结果如下
</span>


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: