Skip to content

Commit a96a08b

Browse files
committed
#222: Count Complete Tree Nodes; solution & tests
1 parent 5b11fab commit a96a08b

File tree

2 files changed

+92
-0
lines changed

2 files changed

+92
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
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+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
using System.Collections;
2+
3+
using NUnit.Framework;
4+
5+
using Problems;
6+
using Problems.Common;
7+
8+
public class CountCompleteTreeNodesTests
9+
{
10+
[TestCaseSource( nameof( TestCases ) )]
11+
public int CountNodesTest( TreeNode root ) =>
12+
new CountCompleteTreeNodes().CountNodes( root );
13+
14+
private static IEnumerable TestCases
15+
{
16+
get
17+
{
18+
yield return new TestCaseData( TreeNode.CreateBST( [1, 2, 3, 4, 5, 6] ) ).Returns( 6 );
19+
20+
yield return new TestCaseData( TreeNode.CreateBST( [] ) ).Returns( 0 );
21+
22+
yield return new TestCaseData( TreeNode.CreateBST( [1] ) ).Returns( 1 );
23+
24+
yield return new TestCaseData( TreeNode.CreateBST( [1, 2, 3, 4] ) ).Returns( 4 );
25+
}
26+
}
27+
}

0 commit comments

Comments
 (0)