Docsity

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

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; ๏‚— }