Binary Tree Traversals (Inorder, Preorder and Postorder)
The inorder enumeration for the tree above is B D A G E C H F I
The preorder enumeration for the tree above is A B D C E G F H I
The postorder enumeration for the tree above is D B G E H I F C A
How to solve different types of tree traversal problem via Prolog?
In prolog, the example tree can be described as follows:
1 | node(a, b, c). |
Inorder
recursive relationship:
node a => b d a g e c h f i => (b d) a (g e c h f i) => left child traversal result + node + right child traversal result
node b (node a’s left child) => b d
node c (node a’s right child) => g e c h f i
1 | % base case |
or
1 | inorder1(Node, List, Tail) :- |
Which inorder traversal algorithm has better time complexity?
Preorder
recursive relationship:
node a => a b d c e g f h i=> a (b d) (c e g f h i) => node + left child traversal result + right child traversal result
node b (node a’s left child) => b d
node c (node a’s right child) => c e g f h i
1 | % base case |
or
1 | preorder1(Node, List, Tail) :- |
Which preorder traversal algorithm has better time complexity?
Postorder
recursive relationship:
node a => d b g e h i f c a=> (d b) (g e h i f c) a => left child traversal result + right child traversal result + node
node b (node a’s left child) => d b
node c (node a’s right child) => g e h i f c
1 | % base case |
or
1 | postorder1(Node, List, Tail) :- |
Which postorder traversal algorithm has better time complexity?
How to solve different types of tree traversal problem via Python?
In python, the example tree can be described as follows:
1 | class TreeNode: |
Inorder (Recursive)
1 | def inorderTraversal(self, root): |
or
1 | def inorderTraversal(root): |
Inorder (Iterative)
1 | def inorderTraversal(root): |
Preorder (Recursive)
1 | def preorderTraversal(root): |
or
1 | def preorderTraversal(root, ret = []): |
Preorder (Iterative)
1 | def preorderTraversal(root): |
or
1 | def preorderTraversal(root): |
Postorder (Recursive)
1 | def postorderTraversal(root): |
or
1 | def postorderTraversal(root): |
Postorder (Iterative)
1 | def postorderTraversal(root): |
Reference
https://www.ida.liu.se/opendsa/OpenDSA/Books/TDDD86_2014/html/BinaryTreeTraversal.html