java - 输出返回字符

标签 java tree

我引用了SOF网上的一些资料后实现了LCA算法。输出结果是一些字符,如下所示。谁能解释一下我下面的代码出了什么问题吗?

package trees;

public class LowestCommonAncestorBinaryTree {

    static class Node {
        Node left;
        Node right;
        int value;

        public Node(int value) {
            left = null;
            right = null;
            this.value = value;
        }
    }
    // Source for below method : http://stackoverflow.com/questions/12056068/finding-least-common-ancestor-in-binary-tree
    public static Node findLca(Node node, int t1, int t2) {
        if(node == null) {
            return null;
        }
        if(node.value > t2 && node.value > t1) {
            // both targets are left
            return findLca(node.left, t1, t2);
        } else if (node.value < t2 && node.value < t1) {
            // both targets are right
            return findLca(node.right, t1, t2);
        } else {
            // either we are diverging or both targets are equal
            // in both cases so we've found the LCA
            // check for actual existence of targets here, if you like
            return node;
        }
    }


    public static void main(String[] args) {

        /**
         * Create a sample Binary Tree. A Binary tree does not have to maintain
         * left <root < right relationship.
         */
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(4);
        root.left.left = new Node(6);
        root.left.right = new Node(5);

        root.right.left = new Node(9);
        root.right.right = new Node(11);
        root.right.right.left = new Node(7);
        root.right.right.right = new Node(3);


        System.out.println("Lowest Common Ancestor of Node 3 and 9 is: "
                + findLca(root, 3,9));


    }

}

这是我得到的输出: 节点 3 和 9 的最低公共(public)祖先是: trees.LowestCommonAncestorBinaryTree$Node@6d06d69c

最佳答案

您只是没有为您的类Node定义toString()。字符串 "trees.LowestCommonAncestorBinaryTree$Node@6d06d69c" 由默认的 toString() 生成。

可以将行打印结果更改为:

System.out.println("Lowest Common Ancestor of Node 3 and 9 is: "
            + findLca(root, 3,9).value);

关于java - 输出返回字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33060939/

相关文章:

java - 在 tomcat 上部署 war 时内存不足

java - 包含 ASSERT 标签的 XML 模式验证

java - tomcat Webapp 之外的 Jar 文件未执行

python - Python的标准库中是否有平衡二叉树的模块?

matlab - 在 matlab 中实现树的最佳方法是什么?

java - 如何让Spark作业完成后自动重启?

java - 用 '%20' 替换空格时出现数组索引越界异常

angular - 无法折叠/展开 Material 树(Angular 6)

python - 如何从图中计算不同排列的最小排除项?

jquery - 如何在 django 中创建嵌套多选树