編寫一個方法combineWith可以添加到IntTree類。該方法接受另一個整數二叉樹作爲參數,並將這兩棵樹組合成一個返回的新的第三棵樹。新樹的結構應該是兩棵原始樹的結構的聯合。它應該在任何原始樹中都有節點的位置有一個節點(或兩者都有)。新樹的節點應存儲一個整數,指示哪個原始樹在該位置有一個節點(如果只有第一棵樹有節點,則爲1,如果只有第二棵樹有節點,則爲2,如果兩棵樹都有節點,則爲3) )。 例如,假設IntTree變量t1和t2已經被初始化和存儲以下樹:我在跟蹤overAllRoot時遇到問題,我的代碼在最後!即時消息面臨無限循環
T3
+---+
| 3 |
___ +---+ ___
/ \
+---+ +---+
| 3 | | 3 |
+---+ +---+
/ \ / \
+---+ +---+ +---+ +---+
| 3 | | 1 | | 2 | | 3 |
+---+ +---+ +---+ +---+
/ \
+---+ +---+
| 1 | | 2 |
+---+ +---+
可以定義私有helper方法來解決這個問題,否則你可能不能調用其他該類的方法,也不創建任何數據結構,如數組,列表等。您的方法不應該更改所比較的兩棵樹之一的結構或內容。
public IntTree combineWith(IntTree t2)
{
IntTree t3 = new IntTree();
while(this.overallRoot != null && t2.overallRoot!= null)
{
t3.overallRoot = new IntTreeNode(3);
// for the 3 combination
if(this.overallRoot.left != null && t2.overallRoot.left != null)
{
t3.overallRoot.left = new IntTreeNode(3) ;
}
if(this.overallRoot.right != null && t2.overallRoot.right != null)
{
t3.overallRoot.right = new IntTreeNode(3) ;
}
// for the 1 combination
if(this.overallRoot.left != null && t2.overallRoot.left == null)
{
t3.overallRoot.left = new IntTreeNode(1) ;
}
if(this.overallRoot.right != null && t2.overallRoot.right == null)
{
t3.overallRoot.right = new IntTreeNode(1) ;
}
// for the 2 combination
if(this.overallRoot.left == null && t2.overallRoot.left != null)
{
t3.overallRoot.left = new IntTreeNode(2) ;
}
if(this.overallRoot.right == null && t2.overallRoot.right != null)
{
t3.overallRoot.right = new IntTreeNode(2) ;
}
}
return t3;
}
嗯。那麼你的問題到底是什麼?如果是「請你爲我做這個問題」,那麼你在這個網站上運氣不會太好。 – 2011-01-08 20:04:12