SlideShare a Scribd company logo
1 of 12
Download to read offline
A perfect left-sided binary tree is a binary tree where every internal node has two children, and
every left child is a leaf. Write an algorithm, based on DFS or BFS, that takes as input an
undirected graph G, and returns whether or not G is (or can be viewed as) a perfect left-sided
binary tree. Analyze the time complexity of your algorithm.
Solution
bfs(G)
{
list L = empty
tree T = empty
choose a starting vertex x
search(x)
while(L nonempty)
remove edge (v,w) from start of L
if w not yet visited
{
add (v,w) to T
search(w)
}
}
dfs(G)
{
list L = empty
tree T = empty
choose a starting vertex x
search(x)
while(L nonempty)
remove edge (v,w) from end of L
if w not yet visited
{
add (v,w) to T
search(w)
}
}
search(vertex v)
{
visit(v);
for each edge (v,w)
add edge (v,w) to end of L
}
mport java.util.*;
public class BST > implements Iterable
{
public static void main(String[] args)
{
Integer[] a = {1,5,2,7,4};
BST bst = new BST();
for(Integer n : a) bst.insert(n);
bst.preOrderTraversal();
System.out.println();
//testing comparator
//build a mirror BST with a rule: Left > Parent > Right
//code for the comparator at the bottom of the file
bst = new BST(new MyComp1());
for(Integer n : a) bst.insert(n);
bst.preOrderTraversal();
System.out.println();
bst.inOrderTraversal();
System.out.println();
for(Integer n : bst) System.out.print(n);
System.out.println();
System.out.println(bst);
//testing restoring a tree from two given traversals
bst.restore(new Integer[] {11,8,6,4,7,10,19,43,31,29,37,49},
new Integer[] {4,6,7,8,10,11,19,29,31,37,43,49});
bst.preOrderTraversal();
System.out.println();
bst.inOrderTraversal();
System.out.println();
//testing diameter
System.out.println("diameter = " + bst.diameter());
//testing width
System.out.println("width = " + bst.width());
}
private Node root;
private Comparator comparator;
public BST()
{
root = null;
comparator = null;
}
public BST(Comparator comp)
{
root = null;
comparator = comp;
}
private int compare(T x, T y)
{
if(comparator == null) return x.compareTo(y);
else
return comparator.compare(x,y);
}
/*****************************************************
*
* INSERT
*
******************************************************/
public void insert(T data)
{
root = insert(root, data);
}
private Node insert(Node p, T toInsert)
{
if (p == null)
return new Node(toInsert);
if (compare(toInsert, p.data) == 0)
return p;
if (compare(toInsert, p.data) < 0)
p.left = insert(p.left, toInsert);
else
p.right = insert(p.right, toInsert);
return p;
}
/*****************************************************
*
* SEARCH
*
******************************************************/
public boolean search(T toSearch)
{
return search(root, toSearch);
}
private boolean search(Node p, T toSearch)
{
if (p == null)
return false;
else
if (compare(toSearch, p.data) == 0)
return true;
else
if (compare(toSearch, p.data) < 0)
return search(p.left, toSearch);
else
return search(p.right, toSearch);
}
/*****************************************************
*
* DELETE
*
******************************************************/
public void delete(T toDelete)
{
root = delete(root, toDelete);
}
private Node delete(Node p, T toDelete)
{
if (p == null) throw new RuntimeException("cannot delete.");
else
if (compare(toDelete, p.data) < 0)
p.left = delete (p.left, toDelete);
else
if (compare(toDelete, p.data) > 0)
p.right = delete (p.right, toDelete);
else
{
if (p.left == null) return p.right;
else
if (p.right == null) return p.left;
else
{
// get data from the rightmost node in the left subtree
p.data = retrieveData(p.left);
// delete the rightmost node in the left subtree
p.left = delete(p.left, p.data) ;
}
}
return p;
}
private T retrieveData(Node p)
{
while (p.right != null) p = p.right;
return p.data;
}
/*************************************************
*
* toString
*
**************************************************/
public String toString()
{
StringBuffer sb = new StringBuffer();
for(T data : this) sb.append(data.toString());
return sb.toString();
}
/*************************************************
*
* TRAVERSAL
*
**************************************************/
public void preOrderTraversal()
{
preOrderHelper(root);
}
private void preOrderHelper(Node r)
{
if (r != null)
{
System.out.print(r+" ");
preOrderHelper(r.left);
preOrderHelper(r.right);
}
}
public void inOrderTraversal()
{
inOrderHelper(root);
}
private void inOrderHelper(Node r)
{
if (r != null)
{
inOrderHelper(r.left);
System.out.print(r+" ");
inOrderHelper(r.right);
}
}
/*************************************************
*
* CLONE
*
**************************************************/
public BST clone()
{
BST twin = null;
if(comparator == null)
twin = new BST();
else
twin = new BST(comparator);
twin.root = cloneHelper(root);
return twin;
}
private Node cloneHelper(Node p)
{
if(p == null)
return null;
else
return new Node(p.data, cloneHelper(p.left), cloneHelper(p.right));
}
/*************************************************
*
* MISC
*
**************************************************/
public int height()
{
return height(root);
}
private int height(Node p)
{
if(p == null) return -1;
else
return 1 + Math.max( height(p.left), height(p.right));
}
public int countLeaves()
{
return countLeaves(root);
}
private int countLeaves(Node p)
{
if(p == null) return 0;
else
if(p.left == null && p.right == null) return 1;
else
return countLeaves(p.left) + countLeaves(p.right);
}
//This method restores a BST given preorder and inorder traversals
public void restore(T[] pre, T[] in)
{
root = restore(pre, 0, pre.length-1, in, 0, in.length-1);
}
private Node restore(T[] pre, int preL, int preR, T[] in, int inL, int inR)
{
if(preL <= preR)
{
int count = 0;
//find the root in the inorder array
while(pre[preL] != in[inL + count]) count++;
Node tmp = new Node(pre[preL]);
tmp.left = restore(pre, preL+1, preL + count, in, inL, inL +count-1);
tmp.right = restore(pre, preL+count+1, preR, in, inL+count+1, inR);
return tmp;
}
else
return null;
}
//The width of a binary tree is the maximum number of elements on one level of the tree.
public int width()
{
int max = 0;
for(int k = 0; k <= height(); k++)
{
int tmp = width(root, k);
if(tmp > max) max = tmp;
}
return max;
}
//rerturns the number of node on a given level
public int width(Node p, int depth)
{
if(p==null) return 0;
else
if(depth == 0) return 1;
else
return width(p.left, depth-1) + width(p.right, depth-1);
}
//The diameter of a tree is the number of nodes
//on the longest path between two leaves in the tree.
public int diameter()
{
return diameter(root);
}
private int diameter(Node p)
{
if(p==null) return 0;
//the path goes through the root
int len1 = height(p.left) + height(p.right) +3;
//the path does not pass the root
int len2 = Math.max(diameter(p.left), diameter(p.right));
return Math.max(len1, len2);
}
/*****************************************************
*
* TREE ITERATOR
*
******************************************************/
public Iterator iterator()
{
return new MyIterator();
}
//pre-order
private class MyIterator implements Iterator
{
Stack> stk = new Stack>();
public MyIterator()
{
if(root != null) stk.push(root);
}
public boolean hasNext()
{
return !stk.isEmpty();
}
public T next()
{
Node cur = stk.peek();
if(cur.left != null)
{
stk.push(cur.left);
}
else
{
Node tmp = stk.pop();
while( tmp.right == null )
{
if(stk.isEmpty()) return cur.data;
tmp = stk.pop();
}
stk.push(tmp.right);
}
return cur.data;
}//end of next()
public void remove()
{
}
}//end of MyIterator
/*****************************************************
*
* the Node class
*
******************************************************/
private class Node
{
private T data;
private Node left, right;
public Node(T data, Node l, Node r)
{
left = l; right = r;
this.data = data;
}
public Node(T data)
{
this(data, null, null);
}
public String toString()
{
return data.toString();
}
} //end of Node
}//end of BST
class MyComp1 implements Comparator
{
public int compare(Integer x, Integer y)
{
return y-x;
}
}

More Related Content

Similar to A perfect left-sided binary tree is a binary tree where every intern.pdf

MAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdfMAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdfadityastores21
 
import java.util.Scanner;class BinaryNode{     BinaryNode left.pdf
import java.util.Scanner;class BinaryNode{     BinaryNode left.pdfimport java.util.Scanner;class BinaryNode{     BinaryNode left.pdf
import java.util.Scanner;class BinaryNode{     BinaryNode left.pdfshaktisinhgandhinaga
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Paulo Morgado
 
Link list part 2
Link list part 2Link list part 2
Link list part 2Anaya Zafar
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaVladimir Kostyukov
 
#include iostream using namespace std; const int nil = 0; cl.docx
#include iostream using namespace std; const int nil = 0; cl.docx#include iostream using namespace std; const int nil = 0; cl.docx
#include iostream using namespace std; const int nil = 0; cl.docxajoy21
 
Required to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docxRequired to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docxdebishakespeare
 
Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdf
Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdfObjective Binary Search Tree traversal (2 points)Use traversal.pp.pdf
Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdfsivakumar19831
 
Что нам готовит грядущий C#7?
Что нам готовит грядущий C#7?Что нам готовит грядущий C#7?
Что нам готовит грядущий C#7?Andrey Akinshin
 
Lecture_10 - Revised.pptx
Lecture_10 - Revised.pptxLecture_10 - Revised.pptx
Lecture_10 - Revised.pptxRedHeart11
 
I have a .java program that I need to modify so that it1) reads i.pdf
I have a .java program that I need to modify so that it1) reads i.pdfI have a .java program that I need to modify so that it1) reads i.pdf
I have a .java program that I need to modify so that it1) reads i.pdfallystraders
 
AvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docx
AvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docxAvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docx
AvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docxrock73
 
import javautilQueue import javautilLinkedList import .pdf
import javautilQueue import javautilLinkedList import .pdfimport javautilQueue import javautilLinkedList import .pdf
import javautilQueue import javautilLinkedList import .pdfADITIEYEWEAR
 
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfarjuncorner565
 
package edu-ser222-m03_02- --- - A binary search tree based impleme.docx
package edu-ser222-m03_02-   ---  - A binary search tree based impleme.docxpackage edu-ser222-m03_02-   ---  - A binary search tree based impleme.docx
package edu-ser222-m03_02- --- - A binary search tree based impleme.docxfarrahkur54
 
Kotlin for Android Developers
Kotlin for Android DevelopersKotlin for Android Developers
Kotlin for Android DevelopersHassan Abid
 

Similar to A perfect left-sided binary tree is a binary tree where every intern.pdf (20)

MAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdfMAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdf
 
import java.util.Scanner;class BinaryNode{     BinaryNode left.pdf
import java.util.Scanner;class BinaryNode{     BinaryNode left.pdfimport java.util.Scanner;class BinaryNode{     BinaryNode left.pdf
import java.util.Scanner;class BinaryNode{     BinaryNode left.pdf
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7
 
Link list part 2
Link list part 2Link list part 2
Link list part 2
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in Scala
 
#include iostream using namespace std; const int nil = 0; cl.docx
#include iostream using namespace std; const int nil = 0; cl.docx#include iostream using namespace std; const int nil = 0; cl.docx
#include iostream using namespace std; const int nil = 0; cl.docx
 
List out of lambda
List out of lambdaList out of lambda
List out of lambda
 
Required to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docxRequired to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docx
 
Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdf
Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdfObjective Binary Search Tree traversal (2 points)Use traversal.pp.pdf
Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdf
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
Что нам готовит грядущий C#7?
Что нам готовит грядущий C#7?Что нам готовит грядущий C#7?
Что нам готовит грядущий C#7?
 
Binary Tree
Binary  TreeBinary  Tree
Binary Tree
 
Lecture_10 - Revised.pptx
Lecture_10 - Revised.pptxLecture_10 - Revised.pptx
Lecture_10 - Revised.pptx
 
I have a .java program that I need to modify so that it1) reads i.pdf
I have a .java program that I need to modify so that it1) reads i.pdfI have a .java program that I need to modify so that it1) reads i.pdf
I have a .java program that I need to modify so that it1) reads i.pdf
 
dynamicList.ppt
dynamicList.pptdynamicList.ppt
dynamicList.ppt
 
AvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docx
AvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docxAvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docx
AvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docx
 
import javautilQueue import javautilLinkedList import .pdf
import javautilQueue import javautilLinkedList import .pdfimport javautilQueue import javautilLinkedList import .pdf
import javautilQueue import javautilLinkedList import .pdf
 
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
 
package edu-ser222-m03_02- --- - A binary search tree based impleme.docx
package edu-ser222-m03_02-   ---  - A binary search tree based impleme.docxpackage edu-ser222-m03_02-   ---  - A binary search tree based impleme.docx
package edu-ser222-m03_02- --- - A binary search tree based impleme.docx
 
Kotlin for Android Developers
Kotlin for Android DevelopersKotlin for Android Developers
Kotlin for Android Developers
 

More from michardsonkhaicarr37

h. What are epigenetic changes How may these contribute to the deve.pdf
h. What are epigenetic changes How may these contribute to the deve.pdfh. What are epigenetic changes How may these contribute to the deve.pdf
h. What are epigenetic changes How may these contribute to the deve.pdfmichardsonkhaicarr37
 
in this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfin this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfmichardsonkhaicarr37
 
How does alcohol affect IPSP and Potassium Why do the ions move.pdf
How does alcohol affect IPSP and Potassium Why do the ions move.pdfHow does alcohol affect IPSP and Potassium Why do the ions move.pdf
How does alcohol affect IPSP and Potassium Why do the ions move.pdfmichardsonkhaicarr37
 
How has the social change driven the development of new information t.pdf
How has the social change driven the development of new information t.pdfHow has the social change driven the development of new information t.pdf
How has the social change driven the development of new information t.pdfmichardsonkhaicarr37
 
Describe the concept of web accessibility.Thank-you!Solution.pdf
Describe the concept of web accessibility.Thank-you!Solution.pdfDescribe the concept of web accessibility.Thank-you!Solution.pdf
Describe the concept of web accessibility.Thank-you!Solution.pdfmichardsonkhaicarr37
 
Good new technologies are a bit like good new roads Their social ben.pdf
Good new technologies are a bit like good new roads Their social ben.pdfGood new technologies are a bit like good new roads Their social ben.pdf
Good new technologies are a bit like good new roads Their social ben.pdfmichardsonkhaicarr37
 
can you help me to solve this. Design a Person class similar to the .pdf
can you help me to solve this. Design a Person class similar to the .pdfcan you help me to solve this. Design a Person class similar to the .pdf
can you help me to solve this. Design a Person class similar to the .pdfmichardsonkhaicarr37
 
Cephalothorax, 6 pairs of jointed appendages. Aquatic, but comes to s.pdf
Cephalothorax, 6 pairs of jointed appendages. Aquatic, but comes to s.pdfCephalothorax, 6 pairs of jointed appendages. Aquatic, but comes to s.pdf
Cephalothorax, 6 pairs of jointed appendages. Aquatic, but comes to s.pdfmichardsonkhaicarr37
 
After reading the codes of ethics posted to the USAOnline site please.pdf
After reading the codes of ethics posted to the USAOnline site please.pdfAfter reading the codes of ethics posted to the USAOnline site please.pdf
After reading the codes of ethics posted to the USAOnline site please.pdfmichardsonkhaicarr37
 
A small boy is lost coming down Mount Washington. The leader of the .pdf
A small boy is lost coming down Mount Washington. The leader of the .pdfA small boy is lost coming down Mount Washington. The leader of the .pdf
A small boy is lost coming down Mount Washington. The leader of the .pdfmichardsonkhaicarr37
 
Address how cooperative binding contributes to SSB function during D.pdf
Address how cooperative binding contributes to SSB function during D.pdfAddress how cooperative binding contributes to SSB function during D.pdf
Address how cooperative binding contributes to SSB function during D.pdfmichardsonkhaicarr37
 
Assembly Code Pep8 Question Write a Pep8 subroutine that is equiva.pdf
Assembly Code Pep8 Question Write a Pep8 subroutine that is equiva.pdfAssembly Code Pep8 Question Write a Pep8 subroutine that is equiva.pdf
Assembly Code Pep8 Question Write a Pep8 subroutine that is equiva.pdfmichardsonkhaicarr37
 
why might bacteria need to alter gene expression when their environm.pdf
why might bacteria need to alter gene expression when their environm.pdfwhy might bacteria need to alter gene expression when their environm.pdf
why might bacteria need to alter gene expression when their environm.pdfmichardsonkhaicarr37
 
Which of the three principles from the Belmont Report were violated .pdf
Which of the three principles from the Belmont Report were violated .pdfWhich of the three principles from the Belmont Report were violated .pdf
Which of the three principles from the Belmont Report were violated .pdfmichardsonkhaicarr37
 
Where is the cell body of the neuron that directly causes SA node ce.pdf
Where is the cell body of the neuron that directly causes SA node ce.pdfWhere is the cell body of the neuron that directly causes SA node ce.pdf
Where is the cell body of the neuron that directly causes SA node ce.pdfmichardsonkhaicarr37
 
Which of the following is FALSE regarding phylogenetic inference met.pdf
Which of the following is FALSE regarding phylogenetic inference met.pdfWhich of the following is FALSE regarding phylogenetic inference met.pdf
Which of the following is FALSE regarding phylogenetic inference met.pdfmichardsonkhaicarr37
 
What is the critical F value for a sample of four observations in th.pdf
What is the critical F value for a sample of four observations in th.pdfWhat is the critical F value for a sample of four observations in th.pdf
What is the critical F value for a sample of four observations in th.pdfmichardsonkhaicarr37
 
what is the main function and sub-functions of a penSolutions.pdf
what is the main function and sub-functions of a penSolutions.pdfwhat is the main function and sub-functions of a penSolutions.pdf
what is the main function and sub-functions of a penSolutions.pdfmichardsonkhaicarr37
 
what are some barriers a company might need to overcome when enterin.pdf
what are some barriers a company might need to overcome when enterin.pdfwhat are some barriers a company might need to overcome when enterin.pdf
what are some barriers a company might need to overcome when enterin.pdfmichardsonkhaicarr37
 
True or False1 The highest abundance of microbial life in soils .pdf
True or False1 The highest abundance of microbial life in soils .pdfTrue or False1 The highest abundance of microbial life in soils .pdf
True or False1 The highest abundance of microbial life in soils .pdfmichardsonkhaicarr37
 

More from michardsonkhaicarr37 (20)

h. What are epigenetic changes How may these contribute to the deve.pdf
h. What are epigenetic changes How may these contribute to the deve.pdfh. What are epigenetic changes How may these contribute to the deve.pdf
h. What are epigenetic changes How may these contribute to the deve.pdf
 
in this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfin this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdf
 
How does alcohol affect IPSP and Potassium Why do the ions move.pdf
How does alcohol affect IPSP and Potassium Why do the ions move.pdfHow does alcohol affect IPSP and Potassium Why do the ions move.pdf
How does alcohol affect IPSP and Potassium Why do the ions move.pdf
 
How has the social change driven the development of new information t.pdf
How has the social change driven the development of new information t.pdfHow has the social change driven the development of new information t.pdf
How has the social change driven the development of new information t.pdf
 
Describe the concept of web accessibility.Thank-you!Solution.pdf
Describe the concept of web accessibility.Thank-you!Solution.pdfDescribe the concept of web accessibility.Thank-you!Solution.pdf
Describe the concept of web accessibility.Thank-you!Solution.pdf
 
Good new technologies are a bit like good new roads Their social ben.pdf
Good new technologies are a bit like good new roads Their social ben.pdfGood new technologies are a bit like good new roads Their social ben.pdf
Good new technologies are a bit like good new roads Their social ben.pdf
 
can you help me to solve this. Design a Person class similar to the .pdf
can you help me to solve this. Design a Person class similar to the .pdfcan you help me to solve this. Design a Person class similar to the .pdf
can you help me to solve this. Design a Person class similar to the .pdf
 
Cephalothorax, 6 pairs of jointed appendages. Aquatic, but comes to s.pdf
Cephalothorax, 6 pairs of jointed appendages. Aquatic, but comes to s.pdfCephalothorax, 6 pairs of jointed appendages. Aquatic, but comes to s.pdf
Cephalothorax, 6 pairs of jointed appendages. Aquatic, but comes to s.pdf
 
After reading the codes of ethics posted to the USAOnline site please.pdf
After reading the codes of ethics posted to the USAOnline site please.pdfAfter reading the codes of ethics posted to the USAOnline site please.pdf
After reading the codes of ethics posted to the USAOnline site please.pdf
 
A small boy is lost coming down Mount Washington. The leader of the .pdf
A small boy is lost coming down Mount Washington. The leader of the .pdfA small boy is lost coming down Mount Washington. The leader of the .pdf
A small boy is lost coming down Mount Washington. The leader of the .pdf
 
Address how cooperative binding contributes to SSB function during D.pdf
Address how cooperative binding contributes to SSB function during D.pdfAddress how cooperative binding contributes to SSB function during D.pdf
Address how cooperative binding contributes to SSB function during D.pdf
 
Assembly Code Pep8 Question Write a Pep8 subroutine that is equiva.pdf
Assembly Code Pep8 Question Write a Pep8 subroutine that is equiva.pdfAssembly Code Pep8 Question Write a Pep8 subroutine that is equiva.pdf
Assembly Code Pep8 Question Write a Pep8 subroutine that is equiva.pdf
 
why might bacteria need to alter gene expression when their environm.pdf
why might bacteria need to alter gene expression when their environm.pdfwhy might bacteria need to alter gene expression when their environm.pdf
why might bacteria need to alter gene expression when their environm.pdf
 
Which of the three principles from the Belmont Report were violated .pdf
Which of the three principles from the Belmont Report were violated .pdfWhich of the three principles from the Belmont Report were violated .pdf
Which of the three principles from the Belmont Report were violated .pdf
 
Where is the cell body of the neuron that directly causes SA node ce.pdf
Where is the cell body of the neuron that directly causes SA node ce.pdfWhere is the cell body of the neuron that directly causes SA node ce.pdf
Where is the cell body of the neuron that directly causes SA node ce.pdf
 
Which of the following is FALSE regarding phylogenetic inference met.pdf
Which of the following is FALSE regarding phylogenetic inference met.pdfWhich of the following is FALSE regarding phylogenetic inference met.pdf
Which of the following is FALSE regarding phylogenetic inference met.pdf
 
What is the critical F value for a sample of four observations in th.pdf
What is the critical F value for a sample of four observations in th.pdfWhat is the critical F value for a sample of four observations in th.pdf
What is the critical F value for a sample of four observations in th.pdf
 
what is the main function and sub-functions of a penSolutions.pdf
what is the main function and sub-functions of a penSolutions.pdfwhat is the main function and sub-functions of a penSolutions.pdf
what is the main function and sub-functions of a penSolutions.pdf
 
what are some barriers a company might need to overcome when enterin.pdf
what are some barriers a company might need to overcome when enterin.pdfwhat are some barriers a company might need to overcome when enterin.pdf
what are some barriers a company might need to overcome when enterin.pdf
 
True or False1 The highest abundance of microbial life in soils .pdf
True or False1 The highest abundance of microbial life in soils .pdfTrue or False1 The highest abundance of microbial life in soils .pdf
True or False1 The highest abundance of microbial life in soils .pdf
 

Recently uploaded

Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxAdelaideRefugio
 
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...Nguyen Thanh Tu Collection
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaEADTU
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文中 央社
 
Trauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical PrinciplesTrauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical PrinciplesPooky Knightsmith
 
How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17Celine George
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjMohammed Sikander
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...EduSkills OECD
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSAnaAcapella
 
How to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptxHow to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptxCeline George
 
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of TransportBasic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of TransportDenish Jangid
 
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMDEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMELOISARIVERA8
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptNishitharanjan Rout
 
SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code ExamplesPeter Brusilovsky
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project researchCaitlinCummins3
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppCeline George
 
Rich Dad Poor Dad ( PDFDrive.com )--.pdf
Rich Dad Poor Dad ( PDFDrive.com )--.pdfRich Dad Poor Dad ( PDFDrive.com )--.pdf
Rich Dad Poor Dad ( PDFDrive.com )--.pdfJerry Chew
 

Recently uploaded (20)

Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptx
 
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
 
Trauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical PrinciplesTrauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical Principles
 
How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17
 
OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
How to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptxHow to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptx
 
ESSENTIAL of (CS/IT/IS) class 07 (Networks)
ESSENTIAL of (CS/IT/IS) class 07 (Networks)ESSENTIAL of (CS/IT/IS) class 07 (Networks)
ESSENTIAL of (CS/IT/IS) class 07 (Networks)
 
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of TransportBasic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
 
Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"
 
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMDEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code Examples
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project research
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio App
 
Rich Dad Poor Dad ( PDFDrive.com )--.pdf
Rich Dad Poor Dad ( PDFDrive.com )--.pdfRich Dad Poor Dad ( PDFDrive.com )--.pdf
Rich Dad Poor Dad ( PDFDrive.com )--.pdf
 

A perfect left-sided binary tree is a binary tree where every intern.pdf

  • 1. A perfect left-sided binary tree is a binary tree where every internal node has two children, and every left child is a leaf. Write an algorithm, based on DFS or BFS, that takes as input an undirected graph G, and returns whether or not G is (or can be viewed as) a perfect left-sided binary tree. Analyze the time complexity of your algorithm. Solution bfs(G) { list L = empty tree T = empty choose a starting vertex x search(x) while(L nonempty) remove edge (v,w) from start of L if w not yet visited { add (v,w) to T search(w) } } dfs(G) { list L = empty tree T = empty choose a starting vertex x search(x) while(L nonempty) remove edge (v,w) from end of L if w not yet visited { add (v,w) to T search(w) } }
  • 2. search(vertex v) { visit(v); for each edge (v,w) add edge (v,w) to end of L } mport java.util.*; public class BST > implements Iterable { public static void main(String[] args) { Integer[] a = {1,5,2,7,4}; BST bst = new BST(); for(Integer n : a) bst.insert(n); bst.preOrderTraversal(); System.out.println(); //testing comparator //build a mirror BST with a rule: Left > Parent > Right //code for the comparator at the bottom of the file bst = new BST(new MyComp1()); for(Integer n : a) bst.insert(n); bst.preOrderTraversal(); System.out.println(); bst.inOrderTraversal(); System.out.println(); for(Integer n : bst) System.out.print(n); System.out.println(); System.out.println(bst); //testing restoring a tree from two given traversals bst.restore(new Integer[] {11,8,6,4,7,10,19,43,31,29,37,49}, new Integer[] {4,6,7,8,10,11,19,29,31,37,43,49}); bst.preOrderTraversal(); System.out.println(); bst.inOrderTraversal();
  • 3. System.out.println(); //testing diameter System.out.println("diameter = " + bst.diameter()); //testing width System.out.println("width = " + bst.width()); } private Node root; private Comparator comparator; public BST() { root = null; comparator = null; } public BST(Comparator comp) { root = null; comparator = comp; } private int compare(T x, T y) { if(comparator == null) return x.compareTo(y); else return comparator.compare(x,y); } /***************************************************** * * INSERT * ******************************************************/ public void insert(T data) { root = insert(root, data); } private Node insert(Node p, T toInsert) {
  • 4. if (p == null) return new Node(toInsert); if (compare(toInsert, p.data) == 0) return p; if (compare(toInsert, p.data) < 0) p.left = insert(p.left, toInsert); else p.right = insert(p.right, toInsert); return p; } /***************************************************** * * SEARCH * ******************************************************/ public boolean search(T toSearch) { return search(root, toSearch); } private boolean search(Node p, T toSearch) { if (p == null) return false; else if (compare(toSearch, p.data) == 0) return true; else if (compare(toSearch, p.data) < 0) return search(p.left, toSearch); else return search(p.right, toSearch); } /***************************************************** * * DELETE *
  • 5. ******************************************************/ public void delete(T toDelete) { root = delete(root, toDelete); } private Node delete(Node p, T toDelete) { if (p == null) throw new RuntimeException("cannot delete."); else if (compare(toDelete, p.data) < 0) p.left = delete (p.left, toDelete); else if (compare(toDelete, p.data) > 0) p.right = delete (p.right, toDelete); else { if (p.left == null) return p.right; else if (p.right == null) return p.left; else { // get data from the rightmost node in the left subtree p.data = retrieveData(p.left); // delete the rightmost node in the left subtree p.left = delete(p.left, p.data) ; } } return p; } private T retrieveData(Node p) { while (p.right != null) p = p.right; return p.data; } /************************************************* *
  • 6. * toString * **************************************************/ public String toString() { StringBuffer sb = new StringBuffer(); for(T data : this) sb.append(data.toString()); return sb.toString(); } /************************************************* * * TRAVERSAL * **************************************************/ public void preOrderTraversal() { preOrderHelper(root); } private void preOrderHelper(Node r) { if (r != null) { System.out.print(r+" "); preOrderHelper(r.left); preOrderHelper(r.right); } } public void inOrderTraversal() { inOrderHelper(root); } private void inOrderHelper(Node r) { if (r != null) { inOrderHelper(r.left);
  • 7. System.out.print(r+" "); inOrderHelper(r.right); } } /************************************************* * * CLONE * **************************************************/ public BST clone() { BST twin = null; if(comparator == null) twin = new BST(); else twin = new BST(comparator); twin.root = cloneHelper(root); return twin; } private Node cloneHelper(Node p) { if(p == null) return null; else return new Node(p.data, cloneHelper(p.left), cloneHelper(p.right)); } /************************************************* * * MISC * **************************************************/ public int height() { return height(root); } private int height(Node p)
  • 8. { if(p == null) return -1; else return 1 + Math.max( height(p.left), height(p.right)); } public int countLeaves() { return countLeaves(root); } private int countLeaves(Node p) { if(p == null) return 0; else if(p.left == null && p.right == null) return 1; else return countLeaves(p.left) + countLeaves(p.right); } //This method restores a BST given preorder and inorder traversals public void restore(T[] pre, T[] in) { root = restore(pre, 0, pre.length-1, in, 0, in.length-1); } private Node restore(T[] pre, int preL, int preR, T[] in, int inL, int inR) { if(preL <= preR) { int count = 0; //find the root in the inorder array while(pre[preL] != in[inL + count]) count++; Node tmp = new Node(pre[preL]); tmp.left = restore(pre, preL+1, preL + count, in, inL, inL +count-1); tmp.right = restore(pre, preL+count+1, preR, in, inL+count+1, inR); return tmp; } else return null;
  • 9. } //The width of a binary tree is the maximum number of elements on one level of the tree. public int width() { int max = 0; for(int k = 0; k <= height(); k++) { int tmp = width(root, k); if(tmp > max) max = tmp; } return max; } //rerturns the number of node on a given level public int width(Node p, int depth) { if(p==null) return 0; else if(depth == 0) return 1; else return width(p.left, depth-1) + width(p.right, depth-1); } //The diameter of a tree is the number of nodes //on the longest path between two leaves in the tree. public int diameter() { return diameter(root); } private int diameter(Node p) { if(p==null) return 0; //the path goes through the root int len1 = height(p.left) + height(p.right) +3; //the path does not pass the root int len2 = Math.max(diameter(p.left), diameter(p.right)); return Math.max(len1, len2);
  • 10. } /***************************************************** * * TREE ITERATOR * ******************************************************/ public Iterator iterator() { return new MyIterator(); } //pre-order private class MyIterator implements Iterator { Stack> stk = new Stack>(); public MyIterator() { if(root != null) stk.push(root); } public boolean hasNext() { return !stk.isEmpty(); } public T next() { Node cur = stk.peek(); if(cur.left != null) { stk.push(cur.left); } else { Node tmp = stk.pop(); while( tmp.right == null ) { if(stk.isEmpty()) return cur.data;
  • 11. tmp = stk.pop(); } stk.push(tmp.right); } return cur.data; }//end of next() public void remove() { } }//end of MyIterator /***************************************************** * * the Node class * ******************************************************/ private class Node { private T data; private Node left, right; public Node(T data, Node l, Node r) { left = l; right = r; this.data = data; } public Node(T data) { this(data, null, null); } public String toString() { return data.toString(); } } //end of Node }//end of BST class MyComp1 implements Comparator {
  • 12. public int compare(Integer x, Integer y) { return y-x; } }