Skip to content

Instantly share code, notes, and snippets.

@zack-w
Created October 4, 2019 10:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zack-w/8be131d7fe13346b531a305b7e6766d5 to your computer and use it in GitHub Desktop.
Save zack-w/8be131d7fe13346b531a305b7e6766d5 to your computer and use it in GitHub Desktop.
/**
@author Benyam Ephrem
These are the 3 fundamental tree traversals all done recursively.
Very basic, very straightforward. These can be done iteratively
as well as in O(1) space, but then they get trickier to implement
but don't worry. If you can grasp these, you can grasp those.
The video to explain this code is here: https://www.youtube.com/watch?v=BHB0B1jFKQc
*/
private class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
/*
n l r
ode eft ight
*/
public void printPreorder(TreeNode root) {
if (root == null) { return; }
System.out.println(root.val);
printPreorder(root.left);
printPreorder(root.right);
}
/*
l n r
eft ode ight
*/
public void printInorder(TreeNode root) {
if (root == null) { return; }
printInorder(root.left);
System.out.println(root.val);
printInorder(root.right);
}
/*
l r n
eft ight ode
*/
public void printPostorder(TreeNode root) {
if (root == null) { return; }
printPostorder(root.left);
printPostorder(root.right);
System.out.println(root.val);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment