Traversing a BST in an in-order fashion and storing the nodes in an array, but the output is not sorted?
I am traversing a Binary Tree
in an in-order manner
to determine if it is a Binary Search Tree
. Here is my code:
class T:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def is_bst(node):
if not node:
return
output = []
is_bst(node.left)
output.append(node.value)
is_bst(node.right)
print(output)
For the above example, the output = [1,3,2,9,7,5]
But this is clearly not correct! - I would usually debug but I am not familiar with running trees/binary trees as inputs. Any idea where my code is going wrong???
Updated code:
class T:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def inOrderTraversal(node,output):
if not node:
return None
is_bst(node.left)
output.append(node.value)
is_bst(node.right)
return
def is_bst(node):
output = []
inOrderTraversal(node,output)
print(output)
For the same example, the output = [1,3,2,9,7,5]
is still wrong
Solution 1:
You create your output
inside the routine, so it's always empty. Then you add the current node's value but you print it at the end of the routine. The result is postorder, not inorder - each node is printed after both its subtrees.
Apart from the code structure your function has wrong name - you actually don't want it to answer whether the tree is BST, you just want it to return the contents:
def dump_tree_inorder(node, output):
if not node:
return
dump_tree_inorder(node.left, output)
output.append(node.value)
dump_tree_inorder(node.right, output)