careercup / CtCI-6th-Edition

Cracking the Coding Interview 6th Ed. Solutions
11.33k stars 4.41k forks source link

Wrong tree traversal sequence #210

Open kaleem68 opened 3 years ago

kaleem68 commented 3 years ago

Java/Ch 04. Trees and Graphs/Introduction/Traversals.java Please fix the recursive call for the preorder and postorder function.

Here is what is found inside Traversals.java

public static void preOrderTraversal(TreeNode node) {
    if (node != null) {
        visit(node);
    inOrderTraversal(node.left);
    inOrderTraversal(node.right);
    }
}

public static void postOrderTraversal(TreeNode node) {
    if (node != null) {
    inOrderTraversal(node.left);
    inOrderTraversal(node.right);
        visit(node);
    }

}

Make it as following public static void preOrderTraversal(TreeNode node) { if (node != null) { visit(node); preOrderTraversal(node.left); preOrderTraversal(node.right); } }

public static void postOrderTraversal(TreeNode node) {
    if (node != null) {
    postOrderTraversal(node.left);
    postOrderTraversal(node.right);
        visit(node);
    }

}