博客
关于我
【java】222. 完全二叉树的节点个数-----了解数据结构,快速了解完全树!
阅读量:360 次
发布时间:2019-03-04

本文共 1001 字,大约阅读时间需要 3 分钟。

给出一个完全二叉树,求出该树的节点个数。

说明:

完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。

示例:

输入:

1
/
2 3
/ \ /
4 5 6

输出: 6

方法一:

简单粗暴,每个结点都遍历一次,用时比较长,不过思路很清晰!

public int countNodes(TreeNode root) {           if(root == null) return 0;        return countNodes(root.left) + countNodes(root.right) + 1;    }

方法二:

获取左右子树的深度。左子树深度 hl ,右子树深度 hr。

有以下两种可能:

1.hl == hr:左子树为满二叉树,直接计算左子树的节点数,然后继续递归右子树。

2.hl > hr:右子树为满树(相比左子树少了一层),直接计算右子树的节点数,然后继续递归左子树。

public int countNodes(TreeNode root) {           if(root == null) return 0;                int hl = depth(root.left);        int hr = depth(root.right);        if(hl == hr) {               return   (int)Math.pow(2,hl)+ countNodes(root.right);         } else {               return   (int)Math.pow(2,hr) + countNodes(root.left);         }    }        private int depth(TreeNode node) {           int d = 0;        while(node != null) {               node = node.left;            d ++;        }                return d;    }

转载地址:http://ztmq.baihongyu.com/

你可能感兴趣的文章
Netty工作笔记0024---SelectionKey API
查看>>
Netty工作笔记0025---SocketChannel API
查看>>
Netty工作笔记0026---NIO 网络编程应用--群聊系统1---编写服务器1
查看>>
Netty工作笔记0027---NIO 网络编程应用--群聊系统2--服务器编写2
查看>>
Netty工作笔记0028---NIO 网络编程应用--群聊系统3--客户端编写1
查看>>
Netty工作笔记0030---NIO与零拷贝原理剖析
查看>>
Netty工作笔记0034---Netty架构设计--线程模型
查看>>
Netty工作笔记0050---Netty核心模块1
查看>>
Netty工作笔记0057---Netty群聊系统服务端
查看>>
Netty工作笔记0058---Netty群聊系统客户端
查看>>
Netty工作笔记0060---Tcp长连接和短连接_Http长连接和短连接_UDP长连接和短连接
查看>>
Netty工作笔记0061---Netty心跳处理器编写
查看>>
Netty工作笔记0063---WebSocket长连接开发2
查看>>
Netty工作笔记0068---Protobuf机制简述
查看>>
Netty工作笔记0070---Protobuf使用案例Codec使用
查看>>
Netty工作笔记0071---Protobuf传输多种类型
查看>>
Netty工作笔记0072---Protobuf内容小结
查看>>
Netty工作笔记0073---Neety的出站和入站机制
查看>>
Netty工作笔记0074---handler链调用机制实例1
查看>>
Netty工作笔记0077---handler链调用机制实例4
查看>>