























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!
























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