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