0% found this document useful (0 votes)
4 views

Chap4_BinaryTree

The document defines a binary tree structure using a Node class and includes functions for various tree traversal methods (InOrder, PreOrder, PostOrder), calculating depth and height, finding a node, and inserting a new node. An example tree is created with root node 1 and its children, and the InOrder traversal is printed before and after inserting nodes with values 10 and 20 under node 3. The code demonstrates basic binary tree operations in Python.

Uploaded by

thanhdat06082006
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Chap4_BinaryTree

The document defines a binary tree structure using a Node class and includes functions for various tree traversal methods (InOrder, PreOrder, PostOrder), calculating depth and height, finding a node, and inserting a new node. An example tree is created with root node 1 and its children, and the InOrder traversal is printed before and after inserting nodes with values 10 and 20 under node 3. The code demonstrates basic binary tree operations in Python.

Uploaded by

thanhdat06082006
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

class Node:

def __init__(self, data):


self.id = data
self.left = None
self.right = None

def InOrder(root):
if root == None:
return
InOrder(root.left)
print(root.id, end = ' ')
InOrder(root.right)

def PreOrder(root):
if root == None:
return
print(root.id, end = ' ')
PreOrder(root.left)
PreOrder(root.right)

def PostOrder(root):
if root == None:
return
PostOrder(root.left)
PostOrder(root.right)
print(root.id, end = ' ')

def Depth(node):
if node == None:
return
if node == root:
return 1
return Height(root) - Height(node) + 1

def Height(node):
if node == None:
return 0
lheight = Height(node.left)
rheight = Height(node.right)
return max(lheight + 1, rheight + 1)

def Find(r, v):


if r == None:
return
if r.id == v:
return r
travel_left = Find(r.left, v)
if travel_left != None:
return travel_left
travel_right = Find(r.right, v)
if travel_right != None:
return travel_right
return None

def Insert(r, u, v):


if r == None:
return
pointer = Find(r, v)
if pointer == None: return
if pointer.left == None:
pointer.left = Node(u)
elif pointer.left != None and pointer.right == None:
pointer.right = Node(u)
return

root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
InOrder(root)
print()
Insert(root, 10, 3)
Insert(root, 20, 3)
InOrder(root)

You might also like