Binary Trees: Understanding the Advantages and Implementation, Lecture notes of Data Structures and Algorithms

An introduction to binary trees, explaining why they are used, their structure, and terms. It covers the Node and Tree classes, methods for finding nodes, inserting nodes, and traversing the tree in different orders. Examples and code snippets are included.

Typology: Lecture notes

2019/2020

Uploaded on 09/17/2020

eman-meslhy
eman-meslhy ๐Ÿ‡ช๐Ÿ‡ฌ

1 document

1 / 31

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Data Structure &
Algorithms
BINARY TREE
BY:
EMAN MESLHY
Eman Meslhy
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f

Partial preview of the text

Download Binary Trees: Understanding the Advantages and Implementation and more Lecture notes Data Structures and Algorithms in PDF only on Docsity!

Data Structure &

Algorithms

BINARY TREE

BY:

EMAN MESLHY

Why Use Binary Trees? ๏‚— Binary tree combine the advantage of two other structures: an order array and linked list. ๏‚— You can search a tree quickly, as you can an ordered array, and you can also insert & delete items quickly, as you can with a linked list. ๏‚— Slow Insertion in an Ordered Array. ๏‚— Slow Searching in a Linked List.

Binary tree ๏‚— Each node in a binary tree has a maximum of two children. ๏‚— Root node, Left child, Right child ๏‚— For any node in the binary tree, if that node contains element elem: ๏‚ก Its left subtree (if nonempty) contains only elements less than elem. ๏‚ก Its right subtree (if nonempty) contains only elements greater than elem.

Tree class ๏‚— class Tree{ ๏‚— private Node root; // the only data field in Tree ๏‚— public void find(int key) { } ๏‚— public void insert(int id, double dd) { } ๏‚— public void delete(int id) { } ๏‚— // various other methods ๏‚— } // end class Tree

Find in java

Question 1 ๏‚— Write a method that adds up the data values in a binary tree and returns the sum. For example, sum(root) of the tree shown returns 16

Answer ๏‚— int sum(node root ){ ๏‚— int sum= 0 ,lsum,rsum; ๏‚— if(root==null) return 0 ; ๏‚— else{ ๏‚— lsum=sum(root.leftchild); ๏‚— rsum=sum(root.rightchild); ๏‚— sum=root.value+lsum+rsum; ๏‚— return sum; ๏‚— }