二叉树1

来源:互联网 发布:淘宝怎么使用不了花呗 编辑:程序博客网 时间:2024/05/17 08:14
二叉树节点类:package binarytree;public class BTNode {    Object data;    BTNode left;    BTNode right;    public BTNode() {    }    public BTNode(Object obj) {        this.data = obj;    }    public BTNode(Object obj, BTNode leftChild, BTNode rightChild) {        this.data = obj;        this.left = leftChild;        this.right = rightChild;    }    @Override    public String toString() {        return data.toString();    }}

测试类:

package binarytree;public class TestTree {    public static void main(String[] args) {        // 叶子节点        BTNode d = new BTNode("D");        BTNode e = new BTNode("E");        BTNode g = new BTNode("G");        // 分支节点        BTNode f = new BTNode("F", g, null);        BTNode b = new BTNode("B", null, d);        BTNode c = new BTNode("C", e, f);        // 根节点        BTNode root = new BTNode("A", b, c);        //递归打印        TestTree.print(root, 0);    }    // 类方法    public static void print(BTNode ref, int level) {        if (ref == null) {            return;        }        /* 逆中序遍历二叉树(右-根-左) */        print(ref.right, level + 1);        // 打印右子树        for (int i = 0; i < level; i++) {     //level控制打印层次缩进            System.out.print("    ");        }        System.out.println(ref.data);       // 打印节点        print(ref.left, level + 1);         // 打印左子树    }}

注:采用逆中序和按层次缩进,是因为把打印结果按顺时针方向旋转90度就能呈现出正常的二叉树形状.

结果:

        F            G    C        EA        D    B



原创粉丝点击