java实现二叉树基本操作

来源:互联网 发布:物演通论知乎 编辑:程序博客网 时间:2024/05/11 17:01

参考他人代码,自己手打一遍,嗯,没有语法错误,哈哈。
代码如下

import java.util.LinkedList;import java.util.List;/**二叉树的链式储存结构 * Created by Administrator on 2017/1/1. */public class TwoTree {   private int[] arry={1,2,3,4,5,6,7,8,9};    private static List<Node> nodeList = null;    /**     * 内部类:节点     */    private static class Node {        Node lChild;        Node rChild;        int data;        Node(int newData){            lChild = null;            rChild = null;            data = newData;        }    }    public void createBinTree(){        nodeList = new LinkedList<Node>();        //将数组转化为Node节点        for (int nodeIndex = 0;nodeIndex<arry.length;nodeIndex++){            nodeList.add(new Node(arry[nodeIndex]));        }        //建立关系树        for (int parentIndex = 0;parentIndex<arry.length/2-1;parentIndex++){            nodeList.get(parentIndex).lChild = nodeList.get(parentIndex*2+1);            nodeList.get(parentIndex).rChild  = nodeList.get(parentIndex*2+2);        }        //对最后一个父节点单独处理,因为最后一个父节点可能没有右孩子        int lastParentIndex = arry.length/2-1;        nodeList.get(lastParentIndex).lChild = nodeList.get(lastParentIndex*2+1);        //如果数组长度为奇数建立右孩子        if (arry.length%2==1){            nodeList.get(lastParentIndex).rChild = nodeList.get(lastParentIndex*2+2);        }    }    /**     * 先序遍历     */    public static void preOrderTraverse(Node node){        if (node==null)            return;        System.out.print(node.data +" ");        preOrderTraverse(node.lChild);        preOrderTraverse(node.rChild);    }    /**     * 中序遍历     */    public static void inOrderTraverse(Node node){        if (node==null)            return;        inOrderTraverse(node.lChild);        System.out.print(node.data + " ");        inOrderTraverse(node.rChild);    }    /**     * 后序遍历     */    public static void postOrderTraverse(Node node){        if (node==null)            return;        postOrderTraverse(node.lChild);        postOrderTraverse(node.rChild);        System.out.print(node.data + " ");    }    public static void main(String[] args){        TwoTree tt = new TwoTree();        tt.createBinTree();        Node root = nodeList.get(0);        System.out.println("先序遍历:");        preOrderTraverse(root);        System.out.println();        System.out.println("中序遍历");        inOrderTraverse(root);        System.out.println();        System.out.println("后序遍历");        postOrderTraverse(root);    }}

其中在创建二叉树的方法里可能有迷惑的地方 。如果有学过c语言版的数据结构那就应该知道,这是二叉树的一个性质。书本上的二叉树大概如下:
这里写图片描述
书上的意思大概是对于节点i(1in

  1. 如果i=1,则节点i是二叉树的跟,无双亲;如果i>1,则其双亲PARENT(i)是节点[i/2],([]的意思是取整的意思,比方说[2.5]就是2)。
  2. 如果2i>n,则节点i无左孩子(节点i为叶子节点);否则其左孩子LCHILD(i)是节点2i。
  3. 如果2i+1>n,则节点i无右孩子;否则其右孩子RCHILD(i)是节点2i+1。

根据这个图来结合性质应该不难理解。
回到这里的代码可以看到左孩子是2i+1,右孩子是2i+2,这是因为第一个节点是从零开始的,并不是从一开始的。

这代码写的比较简单,有时间在补充补充吧。

0 0
原创粉丝点击