我已經寫了一個解決這個問題: https://leetcode.com/problems/count-complete-tree-nodes/
但我正在逐漸TLE。我怎樣才能優化它?「計數完成樹節點」 - 如何優化解決方案?
public class Solution
{
public int countNodes(TreeNode root)
{
if(root==null)
return 0;
int left = count(root.left);
int right = count(root.right);
if(left<=right)
{
return ((int)(Math.pow(2, left)-1) + countNodes(root.right) + 1);
}
else
{
return (countNodes(root.left) + (int)(Math.pow(2, right)-1) + 1);
}
}
public static int count(TreeNode root)
{
int ctr=0;
while(root!=null)
{
ctr++;
root = root.left;
}
return ctr;
}
}
樹在OJ定義爲:
/**
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
這個網站是爲解決發展過程中出現的錯誤。你的問題更適合[codereview.se]。 –
在靜態計數()方法,你只計算節點到左邊,而不是權利。作爲完整性的一部分,您可能會錯過正確的數字。 –
@GeraldSchneider我不知道那個網站。我一定會在未來發布。 –