【数据结构】:求二叉树的的总结点个数

上文(https://blog.csdn.net/qq_44292334/article/details/115145148)我们学习二叉树的建立,以及如何求二叉树的叶子结点个数

本篇文章我们学习如何求二叉树 :总的结点个数

class TreeNode {
    int  val;
    TreeNode leftChild;
    TreeNode rightChild;

    public TreeNode(int val) {
        this.val=val;
    }
}
public class BuildTree {
    public static TreeNode buildTree() {
        //构建二叉树,返回根节点的引用
        // 先构造结点,
        TreeNode a = new TreeNode('4');
        TreeNode b = new TreeNode('2');
        TreeNode c = new TreeNode('6');
        TreeNode d = new TreeNode('1');
        TreeNode e = new TreeNode('3');
        TreeNode f = new TreeNode('5');

        a.leftChild = b;
        a.rightChild = c;

        b.leftChild = d;
        b.rightChild = e;

        c.leftChild = f;
        c.rightChild = null;

        d.leftChild = null;
        d.rightChild = null;

        e.leftChild = null;
        e.rightChild = null;

        f.leftChild = null;
        f.rightChild = null;

        return a;
    }

    private static int n;//记录结点个数
    private static int sumNodeSize(TreeNode root){//方法1
        //求所有结点的个数
        n=0;
        preOder(root);//从根结点出发
        return n;
    }

    private static void preOder(TreeNode root) {
        if(root!=null){
           n++;
            //递归调用,遍历结点的左右子树
            preOder(root.leftChild);
            preOder(root.rightChild);
        }
    }
    private static int sumNodeSize_2(TreeNode root){//方法2
        //求所有结点的个数
        if(root==null){
            return 0;
        }
        return 1+sumNodeSize(root.leftChild)+sumNodeSize(root.rightChild);
    }

    public static void main(String[] args) {
        TreeNode root=buildTree();
        System.out.println("此二叉树的所有节点的个数:"+sumNodeSize(root));
        System.out.println("此二叉树的所有节点的个数:"+sumNodeSize_2(root));
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44292334/article/details/115148633