二叉树的遍历(篇2)计算二叉树节点的个数

来源:互联网 发布:2014淘宝全年销售额 编辑:程序博客网 时间:2024/06/05 19:47

树的大小是树中存在的元素的数量。下面的树的大小是5。

这里写图片描述

使用 Size()函数递归计算树的大小。它的工作原理如下:
树的大小=左子树的大小+ 1 +右子树的大小


算法:

size(树)1.如果树是空的,则返回02.否则     (a)递归获取左子树的大小,即调用           size(tree-> left-subtree)     (a)递归获取右子树的大小,即调用           大小(tree-> right-subtree)     (c)计算树的大小如下:            tree_size = size(left-subtree+ size(right-subtree+1     (d)返回tree_size

代码


// A recursive Java program to calculate the size of the tree/* Class containing left and right child of current   node and key value*/class Node{    int data;    Node left, right;    public Node(int item)    {        data = item;        left = right = null;    }}/* Class to find size of Binary Tree */class BinaryTree{    Node root;    /* Given a binary tree. Print its nodes in level order       using array for implementing queue */    int size()    {        return size(root);    }    /* computes number of nodes in tree */    int size(Node node)    {        if (node == null)            return 0;        else            return(size(node.left) + 1 + size(node.right));    }    public static void main(String args[])    {        /* creating a binary tree and entering the nodes */        BinaryTree tree = new BinaryTree();        tree.root = new Node(1);        tree.root.left = new Node(2);        tree.root.right = new Node(3);        tree.root.left.left = new Node(4);        tree.root.left.right = new Node(5);        System.out.println("The size of binary tree is : "                            + tree.size());    }}

输出:

树的大小是5
0 0
原创粉丝点击