Topic 68 of 78
Preorder Traversal
Overview
Preorder Traversal is a Tree DFS where the order is: Current Node, Left Child, Right Child. You process the parent before its children. It is heavily used when you want to copy or clone a tree, because you must create the parent node before you can attach children to it.
Syntax
Parents are fully processed before any deep dive begins.
Root, Left, Right
java
public void preorder(TreeNode root) {
if (root == null) return;
System.out.print(root.val); // 1. Root (Process)
preorder(root.left); // 2. Left
preorder(root.right); // 3. Right
}Common Pitfalls
- Using Preorder when you actually need sorted data (which requires Inorder).
Interview Tips
- Preorder means the 'Root' is processed PRE (before) its children.
Real-World Example
Creating a completely deep copy of an existing Binary Tree.
example
java
public TreeNode clone(TreeNode root) {
if (root == null) return null;
TreeNode newNode = new TreeNode(root.val); // Preorder creation
newNode.left = clone(root.left);
newNode.right = clone(root.right);
return newNode;
}