Understand Binary Tree Preorder Traversal Problem

Problem Name: Binary Tree Preorder Traversal
Problem Description:

Preorder Traversal Explained

Preorder traversal is a method used to traverse a binary tree by visiting nodes in the following order:

  1. Root Node
  2. Left Subtree
  3. Right Subtree

This traversal is particularly useful for tasks such as copying a tree, expression evaluation, or converting the tree into another structure.


Characteristics

  • Depth-First Approach: Visits nodes deeply before backtracking.
  • Top-Down Order: Processes the root first, then recursively visits the left and right subtrees.
  • Implementation Flexibility: Can be implemented recursively or iteratively using a stack.

How Preorder Traversal Works

  1. Visit the Root: Start with the root node of the tree.
  2. Traverse the Left Subtree: Recursively perform a preorder traversal on the left subtree.
  3. Traverse the Right Subtree: Recursively perform a preorder traversal on the right subtree.

Test Cases

Test Case 1: Simple Tree

Input Tree:

binary tree image Expected Output:
[1, 2, 4, 5, 3]

Test Case 2: Tree with One Child Nodes

Input Tree: binary tree image Expected Output:
[10, 20, 30, 40]

Summary

Preorder traversal follows the order Root → Left → Right. It is a simple and effective method for visiting all the nodes in a tree, ensuring that the root is processed before its children. This method is essential in various tree-related operations and helps in understanding the hierarchical structure of data.

Category:
  • Graphs
Programming Language:
  • Java
Reference Link:

https://leetcode.com/problems/binary-tree-preorder-traversal

Online IDE

Scroll down for output
Java
Output:

Loading component...

Loading component...

Tracking code (View only. In case you want to track the code, click this button):
Main Function:

INPUT: test case 1 in description

OUTPUT: [1, 2, 4, 5, 3]

public static void main(String[] args) {

TreeNode root = new TreeNode(1);

root.left = new TreeNode(2);

root.right = new TreeNode(3);

root.left.left = new TreeNode(4);

root.left.right = new TreeNode(5);

System.out.println("Preorder Traversal:");

preorder(root);

}//function end

Helper Function:

public static void preorder(TreeNode root) {

if (root == null){

return;

}//If End

System.out.print(root.val + " ");

preorder(root.left);

preorder(root.right);

}//function end

Utility Functions and Global variables:

static class TreeNode {

int val;

TreeNode left , right;

TreeNode(int val){

this.val = val;

this.left = this.right = null;

}

} // Class end