Treesandgraphs

327 views

Published on

Published in: Technology, Business
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
327
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
5
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Treesandgraphs

  1. 1. Trees and Graphs Spencer Moran 12/3/13
  2. 2. Properties of a Tree • Tree is a graph where: – n-1 edges – Connected – No cycles • If two of the above are true, then all 3 are true. • Tree questions are usually asked to test your understanding of recursion.
  3. 3. Binary Search Trees • Binary tree is one where each node as at most 2 children. • Binary Search tree is a binary tree where all the descendants to the left of a node are smaller than it and all the descendants to the right are greater than it. • Most interview questions focus on binary or binary search trees.
  4. 4. Binary Search Tree Complexity • • • • • • Lookup: O(log n) Insertion: O(log n) Deletion: O(log n) Smallest/Largest element: O(n) Traversal: O(n) Print in sorted order: O(n)
  5. 5. Heaps • (Usually) binary tree where each node’s children are smaller (or larger in a Min-heap) than it. • Allows for constant time extraction of the largest element in the tree. • Lookup becomes O(n) • Used if extracting the smallest or largest node is paramount
  6. 6. Searching BFS • Queue • Searches minimum depths first, always searches lowest depth last • High memory requirement • Shortest path DFS • Stack • Explores full depth, doesn’t search any particular depth last • Low memory requirement
  7. 7. Traversals • Pre-order: – Explore node, then left children, then right • In-order: – Explore left children, then node, then right • Post-order: – Explore left children, then right, then node • Implemented using simple recursion
  8. 8. Preorder Traversal
  9. 9. Sample Question Find the height of a binary tree.
  10. 10. Strategy • Use recursion • Think of each child as its own separate subtree with that node as the root • Return 1 + the max of left subtree’s height and right subtree’s height
  11. 11. Sample Question Given the value of two nodes in a BST, find the lowest common ancestor. You may assume both values exist in the tree.
  12. 12. Strategy • Uses the left/right descendant property of a BST to traverse through the nodes. • Starting at the root, traverse through the tree. • If both values are greater than the current node, go right. • If both are smaller than the current, go left. • LCA will be the first node you encounter that is between the two nodes you are given.
  13. 13. Other Common Tree Questions • Binary tree to heap • Is Binary tree a BST? • Balance an unbalanced BST (left or right rotation) • Count # of leaves
  14. 14. Graphs • Graph questions are much more complicated and less common. • We will cover graphs during the group meeting.

×