LeetCode -- Count Complete Tree Node

Source: Internet
Author: User

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;}    }

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.