二叉树 求叶子节点数并返回叶子节点个数

编程实现:求二叉树的叶子结点的个数,并打印输出所有叶子结点。

需要先构造一个二叉树,再对二叉树进行遍历,遍历到叶子节点就输出和个数+1

二叉树的结点类:

package com.alibaba.structure.school.two;

// 节点类
public class BinaryNode {

    public T data;
    public BinaryNode left,right;

    // 构造节点
    public BinaryNode(T data,BinaryNode left,BinaryNode right){
        this.data = data;
        this.left = left;
        this.right = right;
    }

    public BinaryNode(T data){
        this(data,null,null);   // this构造方法
    }

    public String toString(){                   // 返回节点数据域的描述字符串
        return this.data.toString();
    }

    public boolean isLeaf(){
        return this.left == null && this.right == null;
    }

}

二叉树类:

package com.alibaba.structure.school.two;

// 二叉树类
public class BinaryTree {

    public BinaryNode root;   // 根节点

    public boolean isEmpty() {    // 判断二叉树是否为空
        return this.root == null;
    }

    public BinaryTree(T[] prelist) {    // 初始的时候构造二叉树
        this.root = create(prelist);
    }

    private int i = 0;
    private BinaryNode create(T[] prelist) {  // {"A","B","D",null,"G",null,null,null,"C","E",null,null,"F","H"};
        BinaryNode p = null;
        if (i < prelist.length) {
            T elem = prelist[i];
            i++;
            if (elem != null) {
                p = new BinaryNode(elem);
                p.left = create(prelist);
                p.right = create(prelist);
            }
        }
        return p;
    }

    int sum = 0;
    public void preorder(){     // 孩子节点优先遍历 ( 先根 )
        int sum = preorder(this.root);
        System.out.println("叶子节点总数为:" + sum);
    }

    private int preorder(BinaryNode p){
        if(p != null){
            if(p.isLeaf()){
                sum +=1;
                System.out.println(p.data.toString() + " ");
            }
            preorder(p.left);
            preorder(p.right);
        }
        return sum;
    }

    public String toString() {
        return toString(this.root);
    }

    private String toString(BinaryNode p) {      // ^ : 表示空
        if (p == null)
            return "^" + " ";
        return p.data.toString() + " " + toString(p.left) + toString(p.right);
    }
}

Main方法:

package com.alibaba.structure.school.two;

// 求叶子节点的个数,并且打印输出叶子节点
public class Main {

    public static void main(String[] args) {
        /*
                         A
                      /   \
                     B     C
                    / \  /  \
                   D  ^ E    F
                  / \  / \  / \
                 ^  G ^  ^ H   ^
                   / \    / \
                  ^  ^   ^   ^

         */
//        String [] prelist = {};
//        String [] prelist = {"A"};
        String [] prelist = {"A","B","D",null,"G",null,null,null,"C","E",null,null,"F","H"};
        BinaryTree bitree = new BinaryTree<>(prelist);
        System.out.println("前序遍历:" +  bitree.toString());  // 中 左 右

        bitree.preorder();  // 返回叶子结点和总和
    }
}

 

你可能感兴趣的:(数据结构,求叶子节点个数)