713585. BST Downward Traversal
BST Downward Traversal
Summary
Given a Binary Search Tree (BST), perform a downward traversal from the root node to all leaf nodes, printing each node's value in descending order.
Key concepts involved: BST, tree traversal.
Detailed Explanation
To solve this problem, we'll use an in-order traversal algorithm with some modifications to achieve the desired downward traversal. We'll start at the root node and recursively visit its left subtree, then the current node itself, and finally its right subtree. This order ensures that we print each node's value in descending order.
Here's a step-by-step breakdown of the solution:
- Start at the root node.
- Recursively traverse the left subtree (if it exists).
- Print the current node's value.
- Recursively traverse the right subtree (if it exists).
To illustrate this process, consider the following ASCII art representation of a BST:
8
/ \
5 12
/ \ / \
2 6 10 14
In this example, the downward traversal from the root node (8) would visit nodes in the order: 12, 14, 10, 6, 8, 5, 2.
The time complexity of this algorithm is O(n), where n is the number of nodes in the BST. The space complexity is O(h), where h is the height of the tree, since we need to store the recursion stack.
Optimized Solutions
Java
public class Main {
public static void downwardTraversal(Node node) {
if (node == null) return;
downwardTraversal(node.right);
System.out.println(node.val);
downwardTraversal(node.left);
}
public static void main(String[] args) {
Node root = new Node(8);
root.left = new Node(5);
root.right = new Node(12);
root.left.left = new Node(2);
root.left.right = new Node(6);
root.right.left = new Node(10);
root.right.right = new Node(14);
downwardTraversal(root);
}
}
class Node {
int val;
Node left, right;
public Node(int val) {
this.val = val;
}
}