2011-11-29 162 views
0

任何人都可以解釋我是如何解決一個表達式樹,當我給x作爲參數?解決二叉樹

例如,我有方程((2 * x))+ 4,讓我們說在參數中,x = 3. 這會給我們10,方法會返回這個。

我想這樣做的方法是遞歸地做,但我不能這樣做,因爲參數必須是雙x。

有什麼想法?

下面是我到目前爲止的代碼。

public double evaluate(double x) throws ExpressionTreeNodeException { 
    ExpressionTreeNode n = new ExpressionTreeNode(); 
    n.setValue(getValue()); 
    n.setType(getType()); 
    if (n.getRightChild() == null && n.getLeftChild() == null){ 
     double RootLeaf = Double.parseDouble(n.getValue()); 
     return RootLeaf; 
    } else { 
     double operand1 = 
     return() 
    } 
} 
+0

爲什麼不能你使用這個遞歸? – Woot4Moo

+0

你能不能解釋一下怎麼遞歸地做呢?如果我想這樣做,我想我需要參數作爲根,這樣我才能繼續通過樹。 –

回答

1

難道你剛纔說的順序的東西:

if (n.getRightChild() == null && n.getLeftChild() == null){ 
    double RootLeaf = Double.parseDouble(n.getValue()); 
    return RootLeaf; 
} else if (n.getLeftChild() == null) { 
    // Evaluate prefix operator -- assume no postfix operators 
    double operand1 = n.getRightChild().evaluate(x); 
    double result = n.getType().evaluateMonadic(operand1); 
    return result; 
} else { 
    // Evaluate diadic operator 
    double operand1 = n.getLeftChild().evaluate(x); 
    double operand2 = n.getRightChild().evaluate(x); 
    double result = n.getType().evaluateDiadic(operand1, operand2); 
    return result; 
} 

(以您的結構自由,因爲我不知道一切的全部意圖。)

(我假設你的結構被定義爲只評估一個變量的函數,這就是爲什麼你通過x而不是傳遞變量值的字典。)

+0

你能解釋一下evaluateMonadic(double)的作用嗎? 它不起作用,因爲getType()返回一個int –

+0

我假設「type」將是運算符的類型,並且「evaluateMonadic」將評估該運算符。也可以是'evaluateMonadic(n.getType(),operand1)'或其他。當然,'evaluateDiadic'會類似,但是對於一個二元操作符來說。 –

+0

有沒有其他方法可以在不使用Monadics的情況下做到這一點?我不確定如何使用它們。 –