Reputation: 121
I've been trying to switch over to Java from Node and one thing I'm wondering about is how to construct a Binary Tree without putting a sorting algorithm in. In Node, I could simply type the following:
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);
What is the Java equivalent to this? This is my current thought process
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; }
}
}
Upvotes: 1
Views: 99
Reputation: 718826
@EJP: There is no need for two classes. Every tree node is a tree.
OP: Can you show me this with one class.
Based on the code 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());
}
}
Upvotes: 1
Reputation: 3807
You can structure your code something like this
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));
}
}
Upvotes: 0