Topic:
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.
Links: http://leetcode.com/problems/count-complete-tree-nodes/
Exercises
The number of nodes in the full binary tree. Note that the only difference between a fully binary tree and a full binary tree of two forks is that the node at the last level of the complete binary tree is dissatisfied, and assumes that the last layer has nodes, all starting from the left. So we can use this property to get the following two conclusions:
- If the height of the Zuozi is equal to the right subtree height, then the right subtree is a complete binary tree, and the left subtree is full of two forks.
- If the height is unequal, then the left word is a complete binary tree, and the right subtree is full of two forks.
- When you ask for height, look only to the left subtree.
Time Complexity-o (Logn * logn), Space complexity-o (1) (regardless of recursive stack)
/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution { Public intcountnodes (TreeNode root) {if(Root = =NULL) return0; intLeftheight =getheight (Root.left); intRightheight =getheight (root.right); if(Leftheight = =rightheight)return(1 << leftheight) +countnodes (root.right); Else return(1 << rightheight) +countnodes (Root.left); } Private intgetheight (TreeNode root) {intHeight = 0; while(Root! =NULL) {root=Root.left; Height++; } returnheight; }}
Off Topic:
High school's best friend's father suddenly died, very sad for him, hope he my condolences and soon cheer up. In fact, in foreign countries, the most worrying is the parents, but under the visa restrictions, perhaps a year can not see parents once. Parents have been nearly 60 years, counted down after the meeting time only dozens of times?? Is this really worth it? This embarrassing dilemma is not to be resolved until after the green card.
Reference:
Https://leetcode.com/discuss/38884/ac-java-code-any-improvement
Https://leetcode.com/discuss/38894/java-solution-clean-code-easy-to-understand
Https://leetcode.com/discuss/38899/easy-short-c-recursive-solution
Https://leetcode.com/discuss/38919/concise-java-iterative-solution-o-logn-2
Https://leetcode.com/discuss/38930/concise-java-solutions-o-log-n-2
Https://leetcode.com/discuss/38930/concise-java-solutions-o-log-n-2
Https://leetcode.com/discuss/39462/c-solution-inspired-by-couple-of-good-ones
Https://leetcode.com/discuss/45260/accepted-clean-java-solution
Https://leetcode.com/discuss/57025/68ms-c-solution-using-binary-search-with-brief-explanation
222. Count Complete Tree Nodes