Question

1. the path length of a binary tree BT is the sum of the depths of...

1. the path length of a binary tree BT is the sum of the depths of all position in BT. write and test a linear-time java method for computing the path length of a binary tree BT. add the method to linkedbinarytree class and write testing code in main method. hint: add method to linkedbinarytree class and write testing in main method


public class LinkedBinaryTree<E> extends AbstractBinaryTree<E> {

//---------------- nested Node class ----------------
/** Nested static class for a binary tree node. */
protected static class Node<E> implements Position<E> {
private E element; // an element stored at this node
private Node<E> parent; // a reference to the parent node (if any)
private Node<E> left; // a reference to the left child (if any)
private Node<E> right; // a reference to the right child (if any)

/**
* Constructs a node with the given element and neighbors.
*
* @param e the element to be stored
* @param above reference to a parent node
* @param leftChild reference to a left child node
* @param rightChild reference to a right child node
*/
public Node(E e, Node<E> above, Node<E> leftChild, Node<E> rightChild) {
element = e;
parent = above;
left = leftChild;
right = rightChild;
}

// accessor methods
public E getElement() { return element; }
public Node<E> getParent() { return parent; }
public Node<E> getLeft() { return left; }
public Node<E> getRight() { return right; }

// update methods
public void setElement(E e) { element = e; }
public void setParent(Node<E> parentNode) { parent = parentNode; }
public void setLeft(Node<E> leftChild) { left = leftChild; }
public void setRight(Node<E> rightChild) { right = rightChild; }
} //----------- end of nested Node class -----------

/** Factory function to create a new node storing element e. */
protected Node<E> createNode(E e, Node<E> parent,
Node<E> left, Node<E> right) {
return new Node<E>(e, parent, left, right);
}

// LinkedBinaryTree instance variables
/** The root of the binary tree */
protected Node<E> root = null; // root of the tree

/** The number of nodes in the binary tree */
private int size = 0; // number of nodes in the tree

// constructor
/** Construts an empty binary tree. */
public LinkedBinaryTree() { } // constructs an empty binary tree

// nonpublic utility
/**
* Verifies that a Position belongs to the appropriate class, and is
* not one that has been previously removed. Note that our current
* implementation does not actually verify that the position belongs
* to this particular list instance.
*
* @param p a Position (that should belong to this tree)
* @return the underlying Node instance for the position
* @throws IllegalArgumentException if an invalid position is detected
*/
protected Node<E> validate(Position<E> p) throws IllegalArgumentException {
if (!(p instanceof Node))
throw new IllegalArgumentException("Not valid position type");
Node<E> node = (Node<E>) p; // safe cast
if (node.getParent() == node) // our convention for defunct node
throw new IllegalArgumentException("p is no longer in the tree");
return node;
}

// accessor methods (not already implemented in AbstractBinaryTree)
/**
* Returns the number of nodes in the tree.
* @return number of nodes in the tree
*/
@Override
public int size() {
return size;
}

/**
* Returns the root Position of the tree (or null if tree is empty).
* @return root Position of the tree (or null if tree is empty)
*/
@Override
public Position<E> root() {
return root;
}

/**
* Returns the Position of p's parent (or null if p is root).
*
* @param p A valid Position within the tree
* @return Position of p's parent (or null if p is root)
* @throws IllegalArgumentException if p is not a valid Position for this tree.
*/
@Override
public Position<E> parent(Position<E> p) throws IllegalArgumentException {
Node<E> node = validate(p);
return node.getParent();
}

/**
* Returns the Position of p's left child (or null if no child exists).
*
* @param p A valid Position within the tree
* @return the Position of the left child (or null if no child exists)
* @throws IllegalArgumentException if p is not a valid Position for this tree
*/
@Override
public Position<E> left(Position<E> p) throws IllegalArgumentException {
Node<E> node = validate(p);
return node.getLeft();
}

/**
* Returns the Position of p's right child (or null if no child exists).
*
* @param p A valid Position within the tree
* @return the Position of the right child (or null if no child exists)
* @throws IllegalArgumentException if p is not a valid Position for this tree
*/
@Override
public Position<E> right(Position<E> p) throws IllegalArgumentException {
Node<E> node = validate(p);
return node.getRight();
}

// update methods supported by this class
/**
* Places element e at the root of an empty tree and returns its new Position.
*
* @param e the new element
* @return the Position of the new element
* @throws IllegalStateException if the tree is not empty
*/
public Position<E> addRoot(E e) throws IllegalStateException {
if (!isEmpty()) throw new IllegalStateException("Tree is not empty");
root = createNode(e, null, null, null);
size = 1;
return root;
}

/**
* Creates a new left child of Position p storing element e and returns its Position.
*
* @param p the Position to the left of which the new element is inserted
* @param e the new element
* @return the Position of the new element
* @throws IllegalArgumentException if p is not a valid Position for this tree
* @throws IllegalArgumentException if p already has a left child
*/
public Position<E> addLeft(Position<E> p, E e)
throws IllegalArgumentException {
Node<E> parent = validate(p);
if (parent.getLeft() != null)
throw new IllegalArgumentException("p already has a left child");
Node<E> child = createNode(e, parent, null, null);
parent.setLeft(child);
size++;
return child;
}

/**
* Creates a new right child of Position p storing element e and returns its Position.
*
* @param p the Position to the right of which the new element is inserted
* @param e the new element
* @return the Position of the new element
* @throws IllegalArgumentException if p is not a valid Position for this tree.
* @throws IllegalArgumentException if p already has a right child
*/
public Position<E> addRight(Position<E> p, E e)
throws IllegalArgumentException {
Node<E> parent = validate(p);
if (parent.getRight() != null)
throw new IllegalArgumentException("p already has a right child");
Node<E> child = createNode(e, parent, null, null);
parent.setRight(child);
size++;
return child;
}

/**
* Replaces the element at Position p with element e and returns the replaced element.
*
* @param p the relevant Position
* @param e the new element
* @return the replaced element
* @throws IllegalArgumentException if p is not a valid Position for this tree.
*/
public E set(Position<E> p, E e) throws IllegalArgumentException {
Node<E> node = validate(p);
E temp = node.getElement();
node.setElement(e);
return temp;
}

/**
* Attaches trees t1 and t2, respectively, as the left and right subtree of the
* leaf Position p. As a side effect, t1 and t2 are set to empty trees.
*
* @param p a leaf of the tree
* @param t1 an independent tree whose structure becomes the left child of p
* @param t2 an independent tree whose structure becomes the right child of p
* @throws IllegalArgumentException if p is not a valid Position for this tree
* @throws IllegalArgumentException if p is not a leaf
*/
public void attach(Position<E> p, LinkedBinaryTree<E> t1,
LinkedBinaryTree<E> t2) throws IllegalArgumentException {
Node<E> node = validate(p);
if (isInternal(p)) throw new IllegalArgumentException("p must be a leaf");
size += t1.size() + t2.size();
if (!t1.isEmpty()) { // attach t1 as left subtree of node
t1.root.setParent(node);
node.setLeft(t1.root);
t1.root = null;
t1.size = 0;
}
if (!t2.isEmpty()) { // attach t2 as right subtree of node
t2.root.setParent(node);
node.setRight(t2.root);
t2.root = null;
t2.size = 0;
}
}

/**
* Removes the node at Position p and replaces it with its child, if any.
*
* @param p the relevant Position
* @return element that was removed
* @throws IllegalArgumentException if p is not a valid Position for this tree.
* @throws IllegalArgumentException if p has two children.
*/
public E remove(Position<E> p) throws IllegalArgumentException {
Node<E> node = validate(p);
if (numChildren(p) == 2)
throw new IllegalArgumentException("p has two children");
Node<E> child = (node.getLeft() != null ? node.getLeft() : node.getRight() );
if (child != null)
child.setParent(node.getParent()); // child's grandparent becomes its parent
if (node == root)
root = child; // child becomes root
else {
Node<E> parent = node.getParent();
if (node == parent.getLeft())
parent.setLeft(child);
else
parent.setRight(child);
}
size--;
E temp = node.getElement();
node.setElement(null); // help garbage collection
node.setLeft(null);
node.setRight(null);
node.setParent(node); // our convention for defunct node
return temp;
}
} //----------- end of LinkedBinaryTree class -----------

0 0
Add a comment Improve this question Transcribed image text
Answer #1

The code :-

// Java program to find maximum path sum in Binary Tree

/* Class containing left and right child of current
node and key value*/
class Node {

   int data;
   Node left, right;

   public Node(int item) {
       data = item;
       left = right = null;
   }
}

// An object of Res is passed around so that the
// same value can be used by multiple recursive calls.
class Res {
   public int val;
}

class BinaryTree {

   // Root of the Binary Tree
   Node root;

   // This function returns overall maximum path sum in 'res'
   // And returns max path sum going through root.
   int findMaxUtil(Node node, Res res)
   {

       // Base Case
       if (node == null)
           return 0;

       // l and r store maximum path sum going through left and
       // right child of root respectively
       int l = findMaxUtil(node.left, res);
       int r = findMaxUtil(node.right, res);

       // Max path for parent call of root. This path must
       // include at-most one child of root
       int max_single = Math.max(Math.max(l, r) + node.data,
                               node.data);


       // Max Top represents the sum when the Node under
       // consideration is the root of the maxsum path and no
       // ancestors of root are there in max sum path
       int max_top = Math.max(max_single, l + r + node.data);

       // Store the Maximum Result.
       res.val = Math.max(res.val, max_top);

       return max_single;
   }

   int findMaxSum() {
       return findMaxSum(root);
   }

   // Returns maximum path sum in tree with given root
   int findMaxSum(Node node) {

       // Initialize result
       // int res2 = Integer.MIN_VALUE;
       Res res = new Res();
       res.val = Integer.MIN_VALUE;

       // Compute and return result
       findMaxUtil(node, res);
       return res.val;
   }

   /* Driver program to test above functions */
   public static void main(String args[]) {
       BinaryTree tree = new BinaryTree();
       tree.root = new Node(10);
       tree.root.left = new Node(2);
       tree.root.right = new Node(10);
       tree.root.left.left = new Node(20);
       tree.root.left.right = new Node(1);
       tree.root.right.right = new Node(-25);
       tree.root.right.right.left = new Node(3);
       tree.root.right.right.right = new Node(4);
       System.out.println("maximum path sum is : " +
                           tree.findMaxSum());
   }
}

Add a comment
Know the answer?
Add Answer to:
1. the path length of a binary tree BT is the sum of the depths of...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Add a non-recursive inorder() method to class LinkedBinaryTree<E> to traverse binary tree. Test inorder() method. Implementation...

    Add a non-recursive inorder() method to class LinkedBinaryTree<E> to traverse binary tree. Test inorder() method. Implementation in Java #########LinkedBinary Tree class######### public class LinkedBinaryTree<E> extends AbstractBinaryTree<E> { //---------------- nested Node class ---------------- /** Nested static class for a binary tree node. */ protected static class Node<E> implements Position<E> { private E element; // an element stored at this node private Node<E> parent; // a reference to the parent node (if any) private Node<E> left; // a reference to the left...

  • Complete HeapPriorityQueue (7 points). In lecture we implemented HeapPriorityQueue using an array-based representation of a heap...

    Complete HeapPriorityQueue (7 points). In lecture we implemented HeapPriorityQueue using an array-based representation of a heap (a complete binary tree whose entries satisfy the heap-order property). For this problem, complete the included HeapPriorityQueue class by using the LinkedBinaryTree class to represent a heap. Hint: the most challenging part of this problem is identifying the last Position in the heap and the next available Position in the heap. It is suggested that you review the array-based heap to better understand how...

  • In Java. How would this method look? LinkedBinaryTree.java import java.util.Iterator; public class LinkedBinaryTree implements BinaryTreeADT {...

    In Java. How would this method look? LinkedBinaryTree.java import java.util.Iterator; public class LinkedBinaryTree implements BinaryTreeADT {    private BinaryTreeNode root;    /**    * Creates an empty binary tree.    */    public LinkedBinaryTree() {        root = null;    }    /**    * Creates a binary tree from an existing root.    */    public LinkedBinaryTree(BinaryTreeNode root) {        this.root = root;    }    /**    * Creates a binary tree with the specified element...

  • In Java Language. Modify the LinkedPostionalList class to support a method swap(p,q) that causes the underlying...

    In Java Language. Modify the LinkedPostionalList class to support a method swap(p,q) that causes the underlying nodes referenced by positions p and q to be exchanged for each other. Relink the existing nodes, do not create any new nodes. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- package lists; import java.util.Iterator; import java.util.NoSuchElementException; public class LinkedPositionalList implements PositionalList { //---------------- nested Node class ---------------- /** * Node of a doubly linked list, which stores a reference to its * element and to both the previous and next...

  • From the code below with Binary Search Tree recurrence T(n)=? use the recursion method and substitution method to solve the recurrence. Find the tightest bound g(n) for T(n) you can for which T(n)= O(...

    From the code below with Binary Search Tree recurrence T(n)=? use the recursion method and substitution method to solve the recurrence. Find the tightest bound g(n) for T(n) you can for which T(n)= O(g(n)). Explain your answer and use recursion tree method. void insert(int data) { struct node *tempNode = (struct node*) malloc(sizeof(struct node)); struct node *current; struct node *parent; tempNode->data = data; tempNode->leftChild = NULL; tempNode->rightChild = NULL; //if tree is empty if(root == NULL) { root = tempNode;...

  • Draw the Binary Tree that is constructed by calling the following methods. BinaryTree T1; T1.addRoot(5); addLeft(T1.root(),...

    Draw the Binary Tree that is constructed by calling the following methods. BinaryTree T1; T1.addRoot(5); addLeft(T1.root(), 10); addRight(T1.root(), 15); BinaryTree T2; T2.addRoot(20); addLeft(T2.root(), 18); addRight(T2.root(), 26); BinaryTree T; T.addRoot(8); attach(T.root, T1, T2); Upload an image showing the tree diagram or show it as following, make sure your result is clear enough to tell the left child or right child or parent node relation. Details regarding the used method can be found under content->others->binary tree code->linkedBinaryTree 1 2 3 5

  • Start with the tree.java program (Listing 8.1) and modify it to create a binary tree from...

    Start with the tree.java program (Listing 8.1) and modify it to create a binary tree from a string of letters (like A, B, and so on) entered by the user. Each letter will be displayed in its own node. Construct the tree so that all the nodes that contain letters are leaves. Parent nodes can contain some non-letter symbol like +. Make sure that every parent node has exactly two children. Don’t worry if the tree is unbalanced. Note that...

  • 1. Write a function in Tree class which returns true if and only if the tree...

    1. Write a function in Tree class which returns true if and only if the tree satisfies the binary search tree property. The function’s header line is public boolean isValidBST() And in the attached code, you just need to finish the function after the comment: “//Instructor hint: please write your code here:” Make sure you execute your code, and the result in the main function after calling your function should be same as the prompt message I write. Clearly you...

  • Using the following implementation of Tree class Node   {   public int iData;              // data item (key)   public...

    Using the following implementation of Tree class Node   {   public int iData;              // data item (key)   public double dData;           // data item   public Node leftChild;         // this node's left child   public Node rightChild;        // this node's right child   public void displayNode()      // display ourself      {      System.out.print('{');      System.out.print(iData);      System.out.print(", ");      System.out.print(dData);      System.out.print("} ");      }   }  // end class Node //------------------------------------------------------------------ import java.io.IOException; import java.util.Stack; public class Tree { private Node root; // first node of tree // ------------------------------------------------------------- public Tree() // constructor { root = null; }...

  • Since we do not want to have to rewrite this code when the element type changes,...

    Since we do not want to have to rewrite this code when the element type changes, this classes uses a Comparator to assist in ordering the elements. You will need to complete the siftUpComparator() and siftDownComparator() methods in the LinkedHeap Class. siftUp §Added element may violate heap-order property §siftUp() restores order starting at added node §Processing will continue working up the tree until: úFinds properly ordered node & parent úReaches the root (reaches node without parent) siftDown §Restores heap’s order...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT