A tree is an abstract data type (ADT) or data structure that simulates a hierarchical tree structure, with a root value and subtrees of children, represented as a set of linked nodes. In computer science, trees are widely used to represent data that has a hierarchical structure, such as file systems, organization charts, and family trees.
If anyone asks you on how do you traverse through the binary tree, you can think of three ways. Those are listed below:
private void postorderTraverse(BinaryNode<T> node) {
if (node != null) {
// Traverse the left sub-tree in post-order
postorderTraverse(node.getLeftChild());
// Traverse the right sub-tree in post-order
postorderTraverse(node.getRightChild());
// Visit the node
System.out.println(node.getData());
}
}
public void postorderTraverse() {
// Start the traversal from the root node
postorderTraverse(root);
}
public void inorderTraverse() {
inorderTraverse(root);
} // end inorderTraverse
private void inorderTraverse(BinaryNode<T> node) {
if (node != null) {
inorderTraverse(node.getLeftChild());
System.out.println(node.getData());
inorderTraverse(node.getRightChild());
} // end if
} // end inorderTraverse
private void postorderTraverse(BinaryNode<T> node) {
if (node != null) {
// Traverse the left sub-tree in post-order
postorderTraverse(node.getLeftChild());
// Traverse the right sub-tree in post-order
postorderTraverse(node.getRightChild());
// Visit the node
System.out.println(node.getData());
}
}
public void postorderTraverse() {
// Start the traversal from the root node
postorderTraverse(root);
}
bstSearch (binarySearchTree, desiredObject) {
// Searches a binary search tree for a given object.
// Returns true if the object is found.
if (binarySearchTree is empty)
return false
else if (desiredObject == object in the root of binarySearchTree)
return true
else if (desiredObject < object in the root of binarySearchTree)
return bstSearch(left subtree of binarySearchTree, desiredObject)
else
return bstSearch(right subtree of binarySearchTree, desiredObject)
}
Computer Science
Sulav Jung Hamal - 2024/08/20