私が抱えている問題は、署名付きのメソッドを書くことです
public static BinaryTree generate(BinaryTree root)
(他のパラメータを追加することは可能です)
このメソッドは、パラメーターとして指定されたようなもの (同じサイズなど) を返すBinaryTree
必要があります。ノードの値を変更する場合にのみ必要です。結果のツリーの各ノードは、 で preorder traversal を使用するときに、同等のノードが処理された位置と等しい値を持つ必要がありますroot
。1から数え始めます。
public class BinaryTree {
public int value;
public BinaryTree left;
public BinaryTree right;
public BinaryTree(int value, BinaryTree left, BinaryTree right)
{
this.value = value;
this.left = left;
this.right = right;
}
}
以下を試してみましたが、正しく動作しません。
public static BinaryTree preOrder(BinaryTree root, int num)
{
//We ALWAYS give 1 as num value!!
if (root == null)
return null;
root.value = num;
preOrder(root.left, ++num);
preOrder(root.right, ++num);
return root;
}
たとえば、BinaryTree がある場合:
3
/ \
2 1
/ \
1 0
(ノードにどんな値があるかは問題ではありません!)
メソッドは次のツリーを返す必要があります。
1
/ \
2 5
/ \
3 4