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, except possibly the last, was completely filled, and all nodes As far left as possible. It can has between 1 and 2h nodes inclusive at the last level H.
Problem Solving Ideas:
Calculate a complete binary tree node, direct recursion will be tle, a good idea is to determine whether it is full two fork tree, and then recursive, Java implementation is as follows:
public int countnodes (TreeNode root) { if (root==null) return 0; int leftheight=1,rightheight=1; TreeNode Temp=root.left; while (temp!=null) { temp=temp.left; leftheight++; } Temp=root.right; while (temp!=null) { temp=temp.right; rightheight++; } if (leftheight==rightheight) return (1<<leftheight)-1; Return Countnodes (Root.left) +countnodes (root.right) +1; }
Java for Leetcode 222 Count complete Tree Nodes