-2

BinaryTree (Search Binary Tree なし) についていくつかの方法を実行する必要がありました。リフレクト(ツリーをリフレクト、ツリーの一部のみをリフレクトするためコードが機能しない)、カット、カット 2 の 3 つの方法を実行できません。コードは次のとおりです。

public class BinaryTree {

    protected class Node {

        Integer element;
        Node left;
        Node right;

        Node(int element) {
            this.element = element;
            left = right = null;
        }

        Node(int element, Node left, Node right) {
            this.element = element;
            this.left = left;
            this.right = right;
        }

            // is leaf?
        boolean isLeaf() {
            return left == null && right == null;
        }
    }

    protected Node root;

    public BinaryTree() {
        root = null;
    }

    /* doesn't work */
    public void reflect() {
        if (root == null)
            return;
        reflect(root);
    }

    protected void reflect(Node node) {
        reflect(node.left);
        reflect(node.right);
        Node temp = new Node(node.left.element);
        node.left.element = node.right.element;
        node.right.element = temp.element;
    }

    /* this method had to trim the tree at level h,
       if h=0, it cut the whole tree. It change the original tree */
    /* doesn't work */
    public void cut(int h) {

    }

    /* i can change parameters */
    protected void cut(Node node, int h) {

    }


    /* this method had to trim the tree at level h,
       if h=0, it cut the whole tree. It doesn't change the original tree, 
       it returns a new tree */
    /* doesn't work */
    public BinaryTree cut2(int h) {

    }


    /* i can change parameters */    
    protected BinaryTree cut2(Node node, int h) {

    }

   }
}

メソッドがcutとcut2を反映することはできません。助けてください、ありがとう!

4

2 に答える 2

0

あなたはほとんどreflect正しかった。新しい Node オブジェクトを作成することは避けてください:

protected void reflect(Node node) {
    if (node != null) {
        reflect(node.left);
        reflect(node.right);
        Node temp = node.left;
        node.left = node.right;
        node.right = temp;
    }
}

に関してはcut

public void cut(int h) {
    if (h == 0) {
        root = null;
    } else {
        cut(root, h - 1);
    }
}

次に、次のように記述できますcut(Node, int)

protected void cut(Node node, int h) {
    if (node != null) {
        if (h == 0) {
            node.left = node.right = null;
        } else {
            cut(node.left, h - 1);
            cut(node.right, h - 1);
        }
    }
}

上記を最初に使用して、自分で解決できるかどうかを確認しcut2てください。

于 2012-10-30T15:52:46.113 に答える
0

これは宿題のようなにおいがします。タグが削除されたとしても、バイナリ ツリーの完全な実装を作成することは正しいことではないと思います。

そうは言っても、これらの両方の方法を実装することについて明確でないことを説明できますか? に必要なツリーのコピーを除いて、それらはほとんど同じですcut2cutInternal(Node n, int currLevel, int h)現在のレベル番号を渡す再帰的なプライベート メソッドを介して実装します。次に、currLevel == h両方のノードをプルーニングして返すだけです。

于 2012-10-30T15:53:08.267 に答える