二刷。
利用Complete Tree的特性,前面N-1层是相等的,可以用POW直接算出来。
主要是最后有可能不完全的一层怎么数。
一刷的办法是每一层都看看,深度,左右相等说明这个点是完全的,用平方算就行,不完全就左+右递归。
public class Solution
{
public int countNodes(TreeNode root)
{
if(root == null) return 0;
int left = countLeft(root.left)+1;
int right = countRight(root.right)+1;
if(left == right) return (1<<left)-1;
else
{
return countNodes(root.left) + countNodes(root.right) + 1;
}
}
public int countLeft(TreeNode root)
{
if(root == null) return 0;
int res = 0;
TreeNode temp = root;
while(temp!=null)
{
temp = temp.left;
res++;
}
return res;
}
public int countRight(TreeNode root)
{
if(root == null) return 0;
int res = 0;
TreeNode temp = root;
while(temp!=null)
{
temp = temp.right;
res++;
}
return res;
}
}
三刷。
算一个树有多少个NODE,是个complete tree which means 除了最后一层都是满的,而且最后一层从左到右填充。
直接遍历TLE。
利用complete的特性,如果一个树是full的 meaning 所有层都是满的,那么总NODE数量是2 ^ 层数 - 1.
所以从ROOT开始,每个NODE都看最左,最右,如果两边深度一样,那么他是full,直接返还2 ^ 深度 - 1。 不是的话,递归。
题不难,难的是算Complexity.
Time Complexlty : O(lgN * lgN) 不是 O(n^2) 因为已经说了是complete tree,不会初恋linkedlist的情况。。
Space Complexity : O(lgN) 递归lgN次就行了。
public class Solution {
public int countNodes(TreeNode root) {
if (root == null) return 0;
int left = 1, right = 1;
TreeNode temp = root.left;
while (temp != null) {
left ++;
temp = temp.left;
}
temp = root.right;
while (temp != null) {
right ++;
temp = temp.right;
}
// this (sub)tree is full
if (left == right) {
return (1 << left) - 1;
} else {
return 1 + countNodes(root.left) + countNodes(root.right);
}
}
}
一刷二刷我还说,* 2给换成 << 1就不TLE了。其实不是,这里指数的算法,何止是把 * 2换成 << 2那么简单。。。