222. Count Complete Tree Nodes
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                222. Count Complete Tree Nodes
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.                        
                                題目:
Given a complete binary tree, count the number of nodes.
Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
解答:
public class Solution {//學(xué)了enum的方法哈哈public enum Direction {LEFT, RIGHT}public int getDepth(TreeNode root, Direction dir) {int depth = 0;//這里是從root開始算起,所以求出來的結(jié)果是實際depth + 1while (root != null) {depth++;if (dir == Direction.LEFT) {root = root.left;} else {root = root.right;}}return depth;}public int countNodes(TreeNode root) {if (root == null) return 0;int leftDepth = getDepth(root, Direction.LEFT);int rightDepth = getDepth(root, Direction.RIGHT);if (leftDepth == rightDepth) {//1 << leftDepth是2^(leftDepth)return (1 << leftDepth) - 1;} else {//這一步很巧妙,把根結(jié)點加上,然后分治左結(jié)點和右結(jié)點,如果是葉子結(jié)點,在countNodes中就返回1return 1 + countNodes(root.left) + countNodes(root.right);}} }總結(jié)
以上是生活随笔為你收集整理的222. Count Complete Tree Nodes的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: quartz分布式集群部署并且可视化配置
- 下一篇: linux如何将json文件导入到mon
