inorder, PreOrder, PostOrder java

https:‮‬//www.lautturi.com
inorder, PreOrder, PostOrder java

Inorder, preorder, and postorder are three types of tree traversal algorithms in Java.

  • Inorder traversal visits the left child, the current node, and then the right child of a binary tree. It is used to traverse the nodes of a tree in ascending order.
  • Preorder traversal visits the current node, the left child, and then the right child of a binary tree. It is used to create a copy of the tree.
  • Postorder traversal visits the left child, the right child, and then the current node of a binary tree. It is used to delete the tree.

Here is an example of how to implement inorder, preorder, and postorder traversal in Java:

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    public TreeNode(int val) {
        this.val = val;
    }
}

public class TreeTraversal {
    public static void inorder(TreeNode root) {
        if (root == null) return;
        inorder(root.left);
        System.out.print(root.val + " ");
        inorder(root.right);
    }

    public static void preorder(TreeNode root) {
        if (root == null) return;
        System.out.print(root.val + " ");
        preorder(root.left);
        preorder(root.right);
    }

    public static void postorder(TreeNode root) {
        if (root == null)return;
        System.out.print(root.val + " ");
        postorder(root.left);
        postorder(root.right);
    }
    
}
Created Time:2017-11-01 22:29:52  Author:lautturi