java - Java中的二叉树不使用add方法

标签 java oop binary-tree

我一直在尝试从 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; }
  }

}

最佳答案

@EJP: There is no need for two classes. Every tree node is a tree.

OP: Can you show me this with one class.

基于代码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());
    }

}

关于java - Java中的二叉树不使用add方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50072119/

相关文章:

java - 应用 BlurMaskFilter 时 TextView 被切断

java - 多语言应用程序问题

c++ - 我可以从派生类中排除基类成员吗?

algorithm - 有多少个不同的有根未标记二叉树正好有 9 个节点并且是左重的?

时间:2019-03-08 标签:c++binarysearchtreeinsert

java - 不变性和图形模型——如何创建它们?

c# - 由其他对象组成的对象在 C# 中失败的优雅方式

Java - Tree 是 Node 的一个实例吗?

python - 如何递归遍历二叉树?

java - Cron 调度程序 "disable pattern"