【问题标题】:Transferring a String array to Binary Tree将字符串数组传输到二叉树
【发布时间】:2022-01-06 22:24:36
【问题描述】:

我正在尝试编写一种可以将数组传输到二叉树的方法。我知道代码不正确,我运行它并希望它会显示一些我可以继续修复它的东西。但它只是继续加载,没有任何错误或结果。哪位大神给点建议,拜托了! 这是 BST 类:

public class BSTNode {
    private String data;

    private BSTNode left;
    private BSTNode right;

    public BSTNode(String data) {
        this.data = data;
        this.right = null;
        this.left = null;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    public BSTNode getLeft() {
        return left;
    }

    public void setLeft(BSTNode left) {
        this.left = left;
    }

    public BSTNode getRight() {
        return right;
    }

    public void setRight(BSTNode right) {
        this.right = right;
    }
}

还有我的方法:

public BSTNode fromArray(String[] array, int start, int end) {
    int i = start;
    BSTNode root = new BSTNode(array[i]);
    BSTNode current = root;
    BSTNode parent = null;
    while (i <= end) {
        if (array[i].compareTo(current.getData()) < 0) {
            parent = current;
            current.setLeft(current); //Should I put current.setLeft(root) here?
        } else {
            parent = current;
            current.setRight(current);
        }
        // Create the new node and attach it to the parent node
        if (array[i].compareTo(parent.getData()) < 0) {
            parent.setLeft(new BSTNode(array[i]));
        } else {
            parent.setRight(new BSTNode(array[i]));
        }
        i++;
    }
    return current;
}

感谢您的宝贵时间!

【问题讨论】:

  • 感谢编辑! @Maurice Perry 看起来好多了!
  • current.setLeft(current);current.setRight(current); 基本上将当前节点链接到自身,这可能导致无限循环。这些电话根本没有意义。试着用这段代码解释你的意图是什么,应该会发生什么应该很明显。此外,您永远不会在循环中更改current,因此parent 也永远不会改变。
  • 我明白为什么它一直在加载。我尝试让它在 2 个变量比较 0 则右转。我研究了一些示例代码,它们只是简单地放入 current.left 或 current.right。但它在我的情况下不起作用,所以我认为 setLeft 会起作用。我不知道如何以正确的方式声明它。感谢您的帮助!

标签: java binary-tree binary-search-tree


【解决方案1】:

在您初始化root 之后,您已经插入了第一个元素,因此您可以立即增加i

您设置了leftright 指针而不跟踪先前的值。

您永远不会在循环中更改current 的值,并且当您立即将其分配给parent 时,您也不会更改parent

您应该返回 root 而不是 current 节点。

这样的事情怎么样:

    while (++i <= end) {
        current = root;
        while (current != null) {
            parent = current;
            if (array[i].compareTo(current.getData()) < 0) {
                current = current.getLeft();
            } else {
                current = current.getRight();
            }
        }
        // Create the new node and attach it to the parent node
        if (array[i].compareTo(parent.getData()) < 0) {
            parent.setLeft(new BSTNode(array[i]));
        } else {
            parent.setRight(new BSTNode(array[i]));
        }
    }
    return root;

更新:

您可以通过将结果保存在变量中来避免冗余比较:

    while (++i <= end) {
        boolean left;
        current = root;
        do {
            parent = current;
            left = array[i].compareTo(current.getData()) < 0;
            if (left) {
                current = current.getLeft();
            } else {
                current = current.getRight();
            }
        } while (current != null);
        // Create the new node and attach it to the parent node
        if (left) {
            parent.setLeft(new BSTNode(array[i]));
        } else {
            parent.setRight(new BSTNode(array[i]));
        }
    }
    return root;

【讨论】:

  • 请注意,您还应该检查开头的start &lt;= end,否则返回null
  • startend 实际上都是包容性的(我宁愿 end 独占,但这不是问题。)
  • @sadetaosa 请在发布 cmets 之前阅读我的回答
  • 非常感谢您的回答。对我真的很有帮助!。我会测试它tmr,如果它运行良好会更新!
  • 附带说明,整个循环体基本上就是 add(value) 方法,即您可以将该代码移动到单独的方法中,然后像 add(array[i]) 一样调用它。
【解决方案2】:
public class Main {

    public static final class Node {

        public static final String NULL = "_";
        public static final String SPLIT = ",";

        private final String val;
        private Node left;
        private Node right;

        public Node(String val) {
            this.val = val;
        }

    }

    public static void main(String... args) {
        Node root = createBinaryTree();
        String str = serialize(root);   // 0,1,3,7,_,9,_,_,_,4,_,_,2,5,_,8,_,_,6,_,_
        Node newRoot = deserialize(str);
    }

    private static String serialize(Node root) {
        StringBuilder buf = new StringBuilder();
        serialize(root, buf);
        return buf.toString();
    }

    private static void serialize(Node node, StringBuilder buf) {
        if (buf.length() > 0)
            buf.append(Node.SPLIT);

        if (node == null)
            buf.append(Node.NULL);
        else {
            buf.append(node.val);
            serialize(node.left, buf);
            serialize(node.right, buf);
        }
    }

    private static Node deserialize(String str) {
        String[] values = str.split(Node.SPLIT);
        return deserialize(values, new AtomicInteger());
    }

    private static Node deserialize(String[] values, AtomicInteger i) {
        if (i.get() >= values.length)
            return null;

        String value = values[i.getAndIncrement()];

        if (Node.NULL.equalsIgnoreCase(value))
            return null;

        Node node = new Node(value);
        node.left = deserialize(values, i);
        node.right = deserialize(values, i);

        return node;

    }

    /*
     *         0
     *       /  \
     *      1    2
     *     / \  / \
     *    3  4 5  6
     *   /      \
     *  7        8
     *   \
     *    9
     */
    private static Node createBinaryTree() {
        Node[] nodes = { new Node("0"), new Node("1"), new Node("2"), new Node("3"),
                new Node("4"), new Node("5"), new Node("6"), new Node("7"),
                new Node("8"), new Node("9") };

        nodes[0].left = nodes[1];
        nodes[0].right = nodes[2];
        nodes[1].left = nodes[3];
        nodes[1].right = nodes[4];
        nodes[2].left = nodes[5];
        nodes[2].right = nodes[6];
        nodes[3].left = nodes[7];
        nodes[5].right = nodes[8];
        nodes[7].right = nodes[9];

        return nodes[0];
    }


}

【讨论】:

    猜你喜欢
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2022-01-18
    • 1970-01-01
    • 2019-10-18
    • 2017-04-17
    • 1970-01-01
    相关资源
    最近更新 更多