|
| 1 | +/** |
| 2 | + * 222 |
| 3 | + * Count Complete Tree Nodes |
| 4 | + ** |
| 5 | + * Given the root of a complete binary tree, |
| 6 | + * return the number of the nodes in the tree. |
| 7 | + * |
| 8 | + * According to Wikipedia (https://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees), |
| 9 | + * every level, except possibly the last, |
| 10 | + * is completely filled in a complete binary tree, |
| 11 | + * and all nodes in the last level are as far left as possible. |
| 12 | + * It can have between 1 and 2h nodes inclusive at the last level h. |
| 13 | + * |
| 14 | + * Design an algorithm that runs in less than O(n) time complexity. |
| 15 | + * |
| 16 | + * Example 1: |
| 17 | + * Input: root = [1,2,3,4,5,6] |
| 18 | + * Output: 6 |
| 19 | + * |
| 20 | + * Example 2: |
| 21 | + * Input: root = [] |
| 22 | + * Output: 0 |
| 23 | + * |
| 24 | + * Example 3: |
| 25 | + * Input: root = [1] |
| 26 | + * Output: 1 |
| 27 | + * |
| 28 | + * Constraints: |
| 29 | + * • The number of nodes in the tree is in the range [0, 5 * 10^4]. |
| 30 | + * • 0 <= Node.val <= 5 * 10^4 |
| 31 | + * • The tree is guaranteed to be complete. |
| 32 | + ** |
| 33 | + * https://leetcode.com/problems/count-complete-tree-nodes/ |
| 34 | +***/ |
| 35 | + |
| 36 | +/** |
| 37 | + * Definition for a binary tree node. |
| 38 | + * public class TreeNode { |
| 39 | + * public int val; |
| 40 | + * public TreeNode left; |
| 41 | + * public TreeNode right; |
| 42 | + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { |
| 43 | + * this.val = val; |
| 44 | + * this.left = left; |
| 45 | + * this.right = right; |
| 46 | + * } |
| 47 | + * } |
| 48 | +***/ |
| 49 | + |
| 50 | +using Problems.Common; |
| 51 | + |
| 52 | +namespace Problems; |
| 53 | + |
| 54 | +public class CountCompleteTreeNodes |
| 55 | +{ |
| 56 | + public int CountNodes( TreeNode root ) |
| 57 | + { |
| 58 | + if ( root is null ) |
| 59 | + { |
| 60 | + return 0; |
| 61 | + } |
| 62 | + |
| 63 | + return 1 + CountNodes( root.left ) + CountNodes( root.right ); |
| 64 | + } |
| 65 | +} |
0 commit comments