Java Tree Implementation: A Comprehensive Guide with Code Examples
This code defines a 'TreeNode' class, which represents a single node in the tree, and a 'Tree' class, which represents the entire tree. The 'Tree' class has methods for inserting nodes into the tree and traversing the tree in-order (i.e., left subtree, root, right subtree) to print out the values in ascending order.
In the 'insert' method, we use a recursive helper function to insert a new node into the tree. If the tree is empty, we create a new node with the given value as the root. If the value is less than the current node's value, we insert it into the left subtree. If the value is greater than the current node's value, we insert it into the right subtree.
In the 'traverseInOrder' method, we use another recursive helper function to traverse the tree in-order. We first traverse the left subtree, then print out the current node's value, and finally traverse the right subtree.
In the 'main' method, we create a new 'Tree' object, insert several nodes into the tree, and then print out the values in order using the 'traverseInOrder' method.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
this.left = null;
this.right = null;
}
}
public class Tree {
TreeNode root;
public Tree() {
this.root = null;
}
public void insert(int val) {
this.root = insertHelper(this.root, val);
}
private TreeNode insertHelper(TreeNode node, int val) {
if (node == null) {
node = new TreeNode(val);
} else if (val < node.val) {
node.left = insertHelper(node.left, val);
} else if (val > node.val) {
node.right = insertHelper(node.right, val);
}
return node;
}
public void traverseInOrder() {
traverseInOrderHelper(this.root);
}
private void traverseInOrderHelper(TreeNode node) {
if (node == null) {
return;
}
traverseInOrderHelper(node.left);
System.out.print(node.val + " ");
traverseInOrderHelper(node.right);
}
public static void main(String[] args) {
Tree tree = new Tree();
tree.insert(5);
tree.insert(2);
tree.insert(7);
tree.insert(1);
tree.insert(3);
tree.insert(6);
tree.insert(8);
System.out.print("In-order traversal: ");
tree.traverseInOrder();
}
}
原文地址: https://www.cveoy.top/t/topic/neb3 著作权归作者所有。请勿转载和采集!