Upgrade to Pro — share decks privately, control downloads, hide ads and more …

CSE205 Lecture 20

CSE205 Lecture 20

Object-Oriented Programming and Data Structures
Binary Tree
(202111)

B546a9b97d993392e4b22b74b99b91fe?s=128

Javier Gonzalez
PRO

September 30, 2021
Tweet

Transcript

  1. jgs CSE 205 Object-Oriented Programming and Data Structures Lecture 20:

    Trees Dr. Javier Gonzalez-Sanchez javiergs@asu.edu javiergs.engineering.asu.edu | javiergs.com PERALTA 230U Office Hours: By appointment
  2. jgs Data Structures 101 Beyond linked list

  3. Javier Gonzalez-Sanchez | CSE205 | Fall 2021 | 3 jgs

    What is the problem with arrays?
  4. Javier Gonzalez-Sanchez | CSE205 | Fall 2021 | 4 jgs

    I introduce you a List, a Linked List
  5. Javier Gonzalez-Sanchez | CSE205 | Fall 2021 | 5 jgs

    What about this?
  6. Javier Gonzalez-Sanchez | CSE205 | Fall 2021 | 6 jgs

    Binary Tree § A non-linear data structure § where each node can have 2 children at most. § keep the tree sorted
  7. jgs Nuts and bolts of Binary Trees Nodes

  8. Javier Gonzalez-Sanchez | CSE205 | Fall 2021 | 8 jgs

    Node class Node { public int value; public Node left public Node right; Node(int value){ value = value; left = null; right = null; } }
  9. Javier Gonzalez-Sanchez | CSE205 | Fall 2021 | 9 jgs

    Tree | insert public class Tree { public void insert(Node node, int value) { if (value < node.value) { if (node.left != null) { insert(node.left, value); } else { System.out.println(" Inserted to left"); node.left = new Node(value); } } else if (value > node.value) { if (node.right != null) { insert(node.right, value); } else { System.out.println(" Inserted to right "); node.right = new Node(value); } } }
  10. Javier Gonzalez-Sanchez | CSE205 | Fall 2021 | 10 jgs

    Tree | Example public static void main(String args[]) { Tree tree = new Tree(); Node root = new Node(5); tree.insert(root, 2); tree.insert(root, 4); tree.insert(root, 8); tree.insert(root, 6); tree.insert(root, 7); tree.insert(root, 3); tree.insert(root, 9); tree.traverseLevelOrder(); } }
  11. Javier Gonzalez-Sanchez | CSE205 | Fall 2021 | 11 jgs

    Tree | Traverse public void traverseInOrder(Node node) { if (node != null) { traverseInOrder(node.left); System.out.print(" " + node.value); traverseInOrder(node.right); } }
  12. Javier Gonzalez-Sanchez | CSE205 | Fall 2021 | 12 jgs

    Questions
  13. jgs CSE 205 Object-Oriented Programming and Data Structures Javier Gonzalez-Sanchez,

    Ph.D. javiergs@asu.edu Fall 2021 Copyright. These slides can only be used as study material for the class CSE205 at Arizona State University. They cannot be distributed or used for another purpose.