Binary Tree preorder, postorder and inorder with java

后端 未结 1 1119
深忆病人
深忆病人 2021-01-27 16:33

I am studying my second semester in computer science, in my data structures class we are seeing binary trees with recursion. We have to make the preorder postorder and inorder t

相关标签:
1条回答
  • 2021-01-27 17:09

    There are some awsome binary tree visualizations online so you can understand it a little better but here are some images I use.

    public void inOrderTraverseTree(Node focusNode) {
        if (focusNode != null) {
            // Traverse the left node
            inOrderTraverseTree(focusNode.leftChild);
            // Visit the currently focused on node
            System.out.println(focusNode);
            // Traverse the right node
            inOrderTraverseTree(focusNode.rightChild);
        }
    }
    

    public void postOrderTraverseTree(Node focusNode) {
        if (focusNode != null) {
            postOrderTraverseTree(focusNode.leftChild);
            postOrderTraverseTree(focusNode.rightChild);
    
            System.out.println(focusNode);
        }
    }
    

    public void preorderTraverseTree(Node focusNode) {
        if (focusNode != null) {
            System.out.println(focusNode);
    
            preorderTraverseTree(focusNode.leftChild);
            preorderTraverseTree(focusNode.rightChild);
        }
    }
    
    0 讨论(0)
提交回复
热议问题