LeetCode -- Count Complete Tree Node
Description:
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, random t 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 2 h nodes random sive at the last level h.
Count the number of nodes in a complete tree.
The full tree is defined as a tree with a height of h + 1, and all nodes in the first h layer are full. For layer h + 1, all nodes without leaves are on the right. This means that some nodes on the left have no leaves, while some nodes on the right have leaves.
Implementation ideas:
Recursively calculates the Left and Right heights. If the height is equal, the Math is directly returned. pow (2, h)-1; if not, recursively calculate the number of left subtree nodes + recursively calculate the number of right subtree nodes + 1;
Implementation Code:
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int x) { val = x; } * } */public class Solution { public int CountNodes(TreeNode root) {if(root == null){return 0;}var leftH = LeftDepth(root.left);var rightH = RightDepth(root.right);if(leftH == rightH){return (int)Math.Pow(2, leftH + 1) - 1;}else{return CountNodes(root.left) + CountNodes(root.right) + 1;} } public int LeftDepth(TreeNode node){var h = 0;while(node != null){node = node.left;h++;}return h; }public int RightDepth(TreeNode node){var h = 0;while(node != null){node = node.right;h++;}return h;} }