【问题标题】:Binary Tree in Java without using add methodJava中的二叉树不使用add方法
【发布时间】:2018-10-08 20:56:55
【问题描述】:

我一直在尝试从 Node 切换到 Java,我想知道的一件事是如何在不放入排序算法的情况下构造二叉树。在 Node 中,我可以简单地键入以下内容:

function TreeNode(val) {
    this.val = val;
    this.left = this.right = null;
}
let tree = new TreeNode(4);
tree.left = new TreeNode(2);
tree.left.left = new TreeNode(1);

Java 相当于什么?这是我目前的思考过程

public class BinaryTree {
    private static TreeNode root;
    public static void main(String[] args) {
        BinaryTree bt = new BinaryTree();
        bt.TreeNode = ??

    }

  public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode(int x) { val = x; }
  }

}

【问题讨论】:

标签: java oop binary-tree


【解决方案1】:

@EJP:不需要两个类。每个树节点都是一棵树。

OP:你能用一节课告诉我这个吗?

基于代码https://stackoverflow.com/a/50072165/139985 ....

public class BinaryTree {
    int data;
    BinaryTree left, right;

    public BinaryTree(int data) {
        super();
        this.data = data;
        this.left = this.right = null; // redundant ...
    }

    public int height() {
        height(this);
    }

    private int height(BinaryTree node) {
        if (node == null) {
            return 0;
        }
        return Math.max(height(node.left), height(node.right)) + 1;
    }

    public static void main(String[] args) {
        BinaryTree tree = new BinaryTree(1);
        tree.left = new BinaryTree(2);
        tree.right = new BinaryTree(3);
        tree.left.right = new BinaryTree(4);

        System.out.println("The height of given binary tree is : " + tree.height());
    }

}

【讨论】:

  • 看起来可行。我不确定如何删除根节点(节点 1)并将根节点设为其他节点(例如 4)?
  • 按分配。 BinaryTree root = ...; root = newRoot; 我们这里有一个开放的数据结构,其中操作由抽象边界之外的代码执行。有了这种 API,就不需要明确区分根节点。实际上,每个节点都是一个子树的根节点。
  • 对我来说看起来不错。取决于要求选择什么设计。
  • 嗯,是的。这适用于所有数据结构。
  • 这可能是我第一次看到一个类的二叉树。在我阅读的任何地方,pople 都倾向于有一个单独的 Node 类。
【解决方案2】:

你可以像这样构造你的代码

class Node {
    int data;
    Node left, right;

    public Node(int data) {
        super();
        this.data = data;
        this.left = this.right = null;
    }

}

public class BinaryTree {
    Node root;

    public int height(Node node) {
        if (node == null)
            return 0;
        return Math.max(height(node.left), height(node.right)) + 1;
    }

    public static void main(String[] args) {
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        tree.root.left.right = new Node(4);

        System.out.println("The height of given binary tree is : " + tree.height(tree.root));
    }

}

【讨论】:

  • 不需要两个类。每个树节点都是一棵树。
  • 但是仍然有两个类而不是一个。
猜你喜欢
  • 2013-06-19
  • 1970-01-01
  • 2013-07-20
  • 1970-01-01
  • 2016-01-21
  • 1970-01-01
  • 1970-01-01
  • 2016-03-13
  • 1970-01-01
相关资源
最近更新 更多