二叉树的遍历(篇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
- 二叉树的遍历(篇2)计算二叉树节点的个数
- 求二叉树的高,节点个数,遍历二叉树
- 第十周项目(3):利用二叉树遍历思想解决问题(1)计算二叉树的节点个数
- 计算二叉树中节点个数,叶节点个数,满节点个数的函数
- 第十周项目3利用二叉树遍历解决问题(计算二叉树节点个数)
- 二叉树的创建、遍历、深度、叶子节点个数
- 二叉树的建立,遍历,节点个数,深度
- java计算二叉树的高度以及叶节点个数
- 计算二叉树的叶子节点个数forC
- 二叉树的节点个数(二叉树)
- 二叉树的层次遍历,叶子节点的个数,是否为完全二叉树等等
- 2013-04-06 二叉树的创建,遍历,统计度为2的节点的个数。
- 二叉树叶子节点个数的计算
- 数据结构五:二叉树的递归遍历,二叉树的叶子节点个数,二叉树的拷贝操作基础学习
- 第十周项目3-利用二叉树遍历思想解决问题(3)求二叉树b的叶子节点个数
- 第十周项目3-利用二叉树遍历思想解决问题(1)计算二叉树节点个数
- 第10周项目3-利用二叉树遍历思想解决问题(1)计算二叉树节点个数
- n节点组成二叉树的个数
- Spring Data之@Query中的org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for DML
- 【大数据技巧】MaxCompute中实现IP地址归属地转换
- 5分钟搭建好最新的ruby环境
- Oracle11g安装
- mysql 分区表
- 二叉树的遍历(篇2)计算二叉树节点的个数
- 未能加载文件或程序集“Newtonsoft.Json”或它的某一个依赖项。找到的程序集清单定义与程序集引用不匹配。 (异常来自 HRESULT:0x80131040)
- 细数阿里云服务器的十二种典型应用场景
- ios NSArray NSMutableArray NSDictionary NSMutableDictionary使用
- 批量打印二维码的软件---使用心得(领跑条码标签打印软件)
- C++文件操作
- mac上使用cocos studio 经常随意奔溃问题解决方法
- SQL SERVER获取索引脚本
- JSON的简单书写(初学),使用Java语言反序列化