递归创建满二叉树并按节点顺序赋值

1.定义节点类:
public class Node<T>  {
    public Node<T> parent;
    public Node<T> leftChild;
    public Node<T> rightChild;
    public T value;
}

2.定义构建满二叉树类

public class FullBiTree {
    /**
     * 递归创建满二叉树
     * @param n 二叉树层数
     * @param index 序数值
     * @return
     */
    public  static  Node<Integer> buildFullBiTree(int n,int index){
        Node<Integer> node=new Node<Integer>();
        node.value = index;
        if(n==1){
            return node;
        }
        else{
            Node<Integer> leftNode=buildFullBiTree(n-1,2*index);
            leftNode.parent=node;
            node.leftChild=leftNode;
            Node<Integer> rightNode=buildFullBiTree(n-1,2*index+1);
            rightNode.parent=node;
            node.rightChild=rightNode;
        }
        return node;
    }
}

3: 深度优先遍历二叉树

    /**
     * 深度优先遍历满二叉树
     * @param root
     */
    public static void dftFullBiTree(Node root){
        if(root!=null){
            System.out.print (root.value+"--");
            dftFullBiTree(root.leftChild);
            dftFullBiTree(root.rightChild);
        }
    }

4: 广度优先遍历二叉树

    /**
     * 广度优先遍历满二叉树
     * @param root
     */
    public static void bftFullBiTree(Node root){
        List<Node> parentList=new ArrayList<Node>();
        List<Node> childList=new ArrayList<Node>();

        int index=1;
        parentList.add(root);
        while(!parentList.isEmpty()){

            for(int m=0;m<parentList.size();m++){
                Node parent=parentList.get(m);
                if(parent.leftChild!=null) {
                    childList.add(parent.leftChild);
                }
                if(parent.rightChild!=null) {
                    childList.add(parent.rightChild);
                }
                System.out.print(parent.value+"--");
            }
            parentList.clear();
            parentList=childList;
            childList=new ArrayList<Node>();
        }
        System.out.println("");
    }

5: 运行

    public static void main(String[] arg){
        int n=4;
        Node<Integer> biTree= buildFullBiTree(n,1);

        bftFullBiTree(biTree);
        dftFullBiTree(biTree);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xyzcto

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值