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 int countNodes(TreeNode root) { if(root == null) return 0; int hl = 0, hr = 0; TreeNode l = root, r = root; while(l != null) { hl++; l = l.left; } while(r != null) { hr++; r = r.right; } if(hl == hr) { return (int)Math.pow(2, hl)-1; } return 1+countNodes(root.left)+countNodes(root.right); }
相关推荐
Count Complete Tree Nodes是LeetCode中的一个常见编程题目,主要考察应聘者对二叉树以及二叉搜索树的理解程度,以及在实际编程过程中解决特定问题的能力。 完整的二叉树节点计数问题通常是这样描述的:给定一个...
《LeetCode 101 - A LeetCode Grinding Guide (C++ Version)》是一本专为C++程序员设计的深入解析LeetCode算法问题的指南。这本书采用彩色版,以直观的方式讲解了各种数据结构和算法,旨在帮助读者磨练编程技能,...
《LeetCode 101 - A LeetCode Grinding Guide (C++ Version)》是一本面向有一定C++编程基础,但缺乏刷题经验读者的教科书和工具书。作者高畅(Chang Gao)基于其在准备实习和秋招过程中对LeetCode题目的整理和刷题...
java java_leetcode-101-symmetric-tree
java java_leetcode-100-same-tree
java java_leetcode-107-binary-tree-level-order-traversal
java java_leetcode-102-binary-tree-level-order-traversal
java java_leetcode-110-balanced-binary-tree
java java_leetcode-maximum-depth-of-binary-tree
java java_leetcode-99-recover-binary-search-tree
java java_leetcode-111-minimum-depth-of-binary-tree
java java_leetcode-114-flatten-binary-tree-to-linked-list
java java_leetcode-105-construct-binary-tree-from-preorder-and-inorde
c c语言_leetcode 0024_swap_nodes_in_pairs.zip
c c语言_leetcode 0025_reverse_nodes_in_k_group.zip
4. leetcode-145-Binary-Tree-Postorder-Traversal.md:第145题,二叉树的后序遍历,是关于树结构和递归的问题。 5. leetCode-5-Longest-Palindromic-Substring.md:第5题,最长回文子串,考察字符串处理和动态规划...
《LeetCode---C++实现》是一本专注于C++编程语言解决LeetCode在线判题平台上的算法问题的书籍。LeetCode是程序员广泛使用的平台,它提供了大量的编程题目来提升编程技能和算法理解,尤其对于准备面试的程序员来说,...
"leetcode-tag-Tree" 指的是 LeetCode 上与“树”相关的标签,这通常意味着这些题目涉及到数据结构中的树型结构。树是一种非线性的数据结构,由若干个节点(或称为顶点)和连接这些节点的边组成,每个节点都可能有零...
leetcode-cli-plugins leetcode-cli 的第 3 方插件。 什么是 如何使用 如何使用 插件 名称 描述 增强的命令 按公司或标签过滤问题 list 不要在同一台计算机上使 Chrome 的会话过期 login 不要在同一台计算机上使 ...