A tree is a graph whose degree of node== # of it's children & is acyclic
Binary tree is a tree with each node having atmost 2 children.
2 ways to traverse each node once:
BFS - level wise
DFS - BY RECURSIVELY TRAVERSING ROOT,LEFT SUBTREE (L) & RIGHT SUBTREE (R)
NOTE: THERE ARE 3! WAYS OF DOING A DFS, BASED ON ORDER OF Root,L,R.
but only 3 are useful :
Root,L,R- preorder traversal
L,Root,R- inorder traversal
L,R,Root- postorder traversal
class Node:
def __init__(self, k):
self.left = None
self.right = None
self.key = k
def inorder(root):
if root != None:
inorder(root.left)
print(root.key)
inorder(root.right)
# Driver Code
root = Node(10)
root.left = Node(20)
root.right = Node(30)
root.right.left = Node(40)
root.right.right = Node(50)
inorder(root)
# time complexity (using recurrence tree method) - O(n)
where,
n == total nodes
# space complexity - O(height of tree)
Note: height can be both n (if each node has exactly 1 child) and
log(n) (if every node has exactly 2 children).
# IMP NOTE : FOR PREORDER AND POSTORDER JUST ORDER OF STATEMENTS CHANGE
for ex:
below is preorder & postorder traversal with same time & space complexity as inorder
def preorder(root):
if root == None:
return
print(root.key)
preorder(root.left)
preorder(root.right)
def postorder(root):
if root == None:
return
preorder(root.left)
preorder(root.right)
print(root.key)