Traversing a tree means to visit all the nodes in a tree exactly once.
In a Pre-Order traversal, we visit all the nodes as follows:
The algorithm for a pre-order traversal of a binary tree is as follows:
while
loop to perform the following steps until the stack is empty:
while
loop will end, then the array that contains the elements in pre-order can be returned.The right child is added to the stack before the left child so that we can pop the left element first, since the stack is a Last-in-First-Out (LIFO) data structure, and in a preorder traversal, the left child should be traversed before the right child.
The slides below illustrate the traversal process:
util
package to use built-in data structures.solution
class, which has the preorderTraversal
method that returns a List
.solution
class. In line 72, we print out the list
returned by the preorderTraversal
method.Refer to the comments provided in the code to understand what every line does.
import java.util.*;//solution classclass Solution {public List<Integer> preorderTraversal(TreeNode root) {//initialize array listList<Integer> preOrder = new ArrayList<>();//if tree is empty then we return empty listif(root == null) return preOrder;//initialize stackStack<TreeNode> st = new Stack<TreeNode>();//push root element to stackst.push(root);//loop runs till stack in not emptywhile(!st.isEmpty()){//pop the top element in stackroot = st.pop();//add it to listpreOrder.add(root.val);//check if left and right elements are presentif(root.right != null) st.push(root.right);if(root.left != null) st.push(root.left);}return preOrder;}}//class to create a new node in treeclass TreeNode {int val;TreeNode left;TreeNode right;TreeNode() {}TreeNode(int val) { this.val = val; }TreeNode(int val, TreeNode left, TreeNode right) {this.val = val;this.left = left;this.right = right;}}public class Main{public static void main(String[] args){//create instances of nodesTreeNode node1 = new TreeNode(1);TreeNode node2 = new TreeNode(2);TreeNode node3 = new TreeNode(3);TreeNode node4 = new TreeNode(4);TreeNode node5 = new TreeNode(5);TreeNode node6 = new TreeNode(6);TreeNode node7 = new TreeNode(7);//creating a binary tree as shown in above representionnode1.left = node2;node1.right = node7;node2.left = node3;node2.right = node4;node4.left = node5;node4.right = node6;//constructing solution objectSolution solution = new Solution();//printing out the returned array list from solutionSystem.out.println(solution.preorderTraversal(node1));}}
solution
class, which has the preorderTraversal
method. preorderTraversal
returns a List
that contains elements traversed in preorder fashion.solution
class and print out the list
returned by the preorderTraversal
method.Refer to the comments provided in the code to understand what every line does.
#solution classclass Solution:# pass root node as parameterdef preorderTraversal(self, root):# initialize listpreorderList = []# initialize stack with root elementstack = [root]# while loop executes till stack is not emptywhile stack:#remove the top element from stacknode = stack.pop()if node:#add it to listpreorderList.append(node.val)#add left and right elemens to stackstack.append(node.right)stack.append(node.left)return preorderList#class to create tree nodeclass TreeNode:def __init__(self, val=0, left=None, right=None):self.val = valself.left = leftself.right = right# create node instancesnode1 = TreeNode(1);node2 = TreeNode(2);node3 = TreeNode(3);node4 = TreeNode(4);node5 = TreeNode(5);node6 = TreeNode(6);node7 = TreeNode(7);# creates binary tree as shown in representationnode1.left = node2;node1.right = node7;node2.left = node3;node2.right = node4;node4.left = node5;node4.right = node6;# print the elements in preorder returned by solutionprint(Solution().preorderTraversal(node1))