222. Count Complete Tree Nodes
Given a complete binary tree, count the number of nodes. Note: 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. Example: Input: 1 / \ 2 3 / \ / 4 5 6 Output: 6 https://leetcode.com/problems/count-complete-tree-nodes/discuss/61958/Concise-Java-solutions-O(log(n)2) https://www.cnblogs.com/yrbbest/p/4993469.html http://www.cnblogs.com/grandyang/p/4567827.html For those who are confused with (1 << leftDepth) - 1; This is done to find the nodes when depth is known. Suppose there are N nodes in a tree, Then depth=(log2(n+1)) 1 node gives log2(2) = 1 3 nodes gives log2(4) = 2 7 nodes gives log2(8) = 3 15 nodes gives log2(16) = 4 what we are doing in this line (1 << leftDepth) - 1 is given Depth we will find Number of nodes, N = (2^depth-)1. This is a clean and smart solution, my understanding is as follows: 1. A fully completed tree has node number: count = 2 ^ depth - 1 for example: [1,2,3] depth is 2 count = 2 ^ 2 - 1 = 3 2. Compare left height and right height, if equal, use the formular, otherwise recurvisely search left and right at next level 3. The search pattern is very similar to binary search, the difference of heights ethier exsits in left side, or right side 4. Due to the reason stated in point 3, the time complexity is h ^ 2, there is h times for each level, and h times for calculating height at each level
https://leetcode.com/problems/count-complete-tree-nodes/discuss/61958/Concise-Java-solutions-O(log(n)2)
posted on 2018-11-08 16:52 猪猪🐷 阅读(93) 评论(0) 收藏 举报
浙公网安备 33010602011771号