Beginner tree algorithms | Graph Theory

WilliamFiset · Beginner ·⚡ Algorithms & Data Structures ·6y ago

Key Takeaways

This video covers beginner tree algorithms, specifically calculating the sum of leaf node values and finding the height of a binary tree, using depth-first search and recursive functions.

Full Transcript

[Music] [Music] hello and welcome my name is William and in today's video we're going to look at some simple tree algorithms this video is aimed at all you beginners just starting out who are still learning how to write code and especially learning to write recursive code we're going to have a look at two problems and these are the types of problems which you might encounter as a warm-up question during a job interview all right let's get started with our first problem for this problem we need to find the sum of all the leaf node values in a tree for instance given this tree we want to sum up the values of all the bottom nodes that would be these nodes in red for a total of nine now if you're really keen you can pause the video and give this problem a try to solve this problem all we need to do is perform a tree traversal and sum up the values of the leaf nodes as we encounter them during the traversal two popular traversal algorithms are doing a breadth-first search and a depth-first search now on trees the preferred traversal method is typically a depth-first search because it lends itself to be easily implemented recursively so that's what we're going to do it's pretty simple watch how the algorithm does it what you do is you start at the root and then you plunge down the tree depth-first at the end we sum up all the values and we can see that the sum of the leaf nodes is 9 now let's look at some pseudocode for how this is implemented the algorithm is quite short but it may look strange at first if you haven't seen much recursive code we call the leaf sum function by passing in a reference to the root node as a starting point inside the leaf sum function the first thing we do is handle the special case where we're given an empty tree and if this is the situation then we return 0 next we check if the current node is a leaf node and if it is then we return the value stored in the leaf node the is leaf method checks if a node is a leaf node by counting all its children if the number of child nodes is 0 then we know that the current node is indeed a leaf node if the node is not a leaf node then we iterate over all its children and call the leaf some method recursively summing over the return values this ensures that we traverse the entire tree and properly accumulate values finally once we are finished computing the sum for this node and its subtree returned the total and that's all for summing up the leaf node values in a tree our second problem today is a classic problem in computer science which is to find the height of a binary tree the height of a tree is defined as the number of edges from the root node to the lowest leaf of the tree here the leftmost tree has a height of 0 because it has no edges the middle tree has height of 1 and the rightmost tree has a height of 3 because the longest path from the root to the lowest leaf is 3 to solve this problem we're going to break it down and define a new function called H of X which returns the height of the subtree rooted at node X this new function allows us to start thinking not only about the height of a tree as whole but also the height of the sub-trees within our tree which are going to help us find the overall height for example on this slide h of a has a value of 3 but h of b has a value of 2 and h of e has a value of 0 by themselves leaf nodes such as node E don't have children so they don't add any additional height to the tree so we conclude that as a base case the height of any leaf node should be 0 now assuming Note X is not a leaf node we're able to formulate a recurrence relation for the height which is that the height of a subtree rooted at node X is the maximum of the height of X's left and right subtrees plus 1 let's have a closer look at how this works with an example suppose we have a tree and we want to compute its height so we start at the root and then we recursively Traverse down the tree depth first when we encounter a leaf node we give it a height of 0 and return we can't compute the height of a node until we know the height of all children so we visit the right node the right node is also a leaf node so it gets a height of 0 on the callback we have visited both children of the current node so we take the maximum heights of the left and the right children and add one for a total of 1 we just finished exploring the right half the tree now let's finish the left side it doesn't matter which side you do first as long as you explore the whole tree while you do your depth-first search we have found another leaf node so it gets a height of 0 we found another leaf node and another leaf node on the kullback-- take the max and add 1 take the max and add one again finally compute the height of the final node by taking the max and adding one and there you have it how to find the height of a tree let's have a look at some pseudocode shall we this is the tree height function it is responsible for computing the height of the tree you would start by calling this function by passing in the trees root node as we did for the leaf sum function the first thing we do is handle the empty tree case the height of an empty tree is undefined so return minus one next we check whether the current node is a leaf node by checking if both its left and right child nodes are null and return zero if either of them are not null then we know that this node has more children and we need to keep digging further down the tree in the event we haven't found the leaf node return the maximum height of the left subtree and the right subtree plus one I want to take a moment and go back to the previous statement and remark on a simplification we can exploit what do you reckon happens if we remove checking whether a node is a leaf node or not do you think the algorithm will still behave correctly pause the video and think this over oddly enough removing the leaf node check still makes the algorithm work correctly this works because the base case has adopted a new meaning instead of the base case checking for leaf nodes it's now checking whether a node is null and returning minus one now returning minus one is not only for handling the empty tree case but also to help in correcting for the right tree height let's see what I mean by correcting for the right height if our new base case is now checking for null nodes instead of leaf nodes then our tree is one unit taller so we need to correct for that for the sake of being thorough let's see how the height is calculated with this new base case once we reach a null node to return -1 on the recursive call back remember that we always add +1 with our recurrence so when we add up the counts you see that we get the correct height of 3 and that's how you compute the height of a tree in practice if you're designing a data structure where the tree height is important you can dynamically keep track of the height as you create the tree and insert nodes instead of fully completing the height every time like we're doing here but of course that isn't always doable alright folks thanks for watching please like and subscribe if you learned something and I will catch you [Music]

Original Description

Beginner tree algorithms: tree height and leaf sum Support me by purchasing the full graph theory course on Udemy which includes additional problems, exercises and quizzes not available on YouTube: https://www.udemy.com/course/graph-theory-algorithms Algorithms repository: https://github.com/williamfiset/algorithms#tree-algorithms Next video (rooting a tree): https://youtu.be/2FFq2_je7Lg Video slides: https://github.com/williamfiset/Algorithms/tree/master/slides 0:00 Intro 0:40 Problem 1: Leaf node sum 2:19 Problem 1: Pseudocode 3:32 Problem 2: Tree height 6:50 Problem 2: Pseudocode 8:25 Problem 2: Tree height simplification =================================== Practicing for interviews? I have used, and recommend `Cracking the Coding Interview` which got me a job at Google. Link on Amazon: https://amzn.to/3cvMof5 A lot of the content on this channel is inspired by the book `Competitive Programming` by Steven Halim which I frequently use as a resource and reference. Link on Amazon: https://amzn.to/3wC2nix
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from WilliamFiset · WilliamFiset · 0 of 60

← Previous Next →
1 JES Image Manipulation - 2 - Installation
JES Image Manipulation - 2 - Installation
WilliamFiset
2 JES Image Manipulation - 3 - User Interface
JES Image Manipulation - 3 - User Interface
WilliamFiset
3 JES Image Manipulation - 5 - Negative
JES Image Manipulation - 5 - Negative
WilliamFiset
4 JES Image Manipulation - 6 - Black & White
JES Image Manipulation - 6 - Black & White
WilliamFiset
5 JES Image Manipulation - 4 - Grayscale
JES Image Manipulation - 4 - Grayscale
WilliamFiset
6 JES Image Manipulation - 8 - Blur
JES Image Manipulation - 8 - Blur
WilliamFiset
7 JES Image Manipulation - 7 - Edge Detection
JES Image Manipulation - 7 - Edge Detection
WilliamFiset
8 JES Image Manipulation - 9 - Blend
JES Image Manipulation - 9 - Blend
WilliamFiset
9 JES Image Manipulation - 10 - Matte
JES Image Manipulation - 10 - Matte
WilliamFiset
10 JES Image Manipulation - 13 - Rotate90
JES Image Manipulation - 13 - Rotate90
WilliamFiset
11 JES Image Manipulation - 12 - Mirroring Picture
JES Image Manipulation - 12 - Mirroring Picture
WilliamFiset
12 JES Image Manipulation - 11  - Crop Image
JES Image Manipulation - 11 - Crop Image
WilliamFiset
13 JES Image Manipulation - 14 - Stretch picture
JES Image Manipulation - 14 - Stretch picture
WilliamFiset
14 Java Fractal Explorer [6/8]
Java Fractal Explorer [6/8]
WilliamFiset
15 Java Fractal Explorer [4/8]
Java Fractal Explorer [4/8]
WilliamFiset
16 Java Fractal Explorer [8/8]
Java Fractal Explorer [8/8]
WilliamFiset
17 Java Fractal Explorer [5/8]
Java Fractal Explorer [5/8]
WilliamFiset
18 Java Fractal Explorer [2/8]
Java Fractal Explorer [2/8]
WilliamFiset
19 Java Fractal Explorer [7/8]
Java Fractal Explorer [7/8]
WilliamFiset
20 Java Fractal Explorer [1/8]
Java Fractal Explorer [1/8]
WilliamFiset
21 Java Fractal Explorer [3/8]
Java Fractal Explorer [3/8]
WilliamFiset
22 Introduction [Programming Competition Problems]
Introduction [Programming Competition Problems]
WilliamFiset
23 String Manipulation 1 [Programming Competition Problems]
String Manipulation 1 [Programming Competition Problems]
WilliamFiset
24 String Manipulation 2 [Programming Competition Problems]
String Manipulation 2 [Programming Competition Problems]
WilliamFiset
25 Graph Theory 1 [Programming Competition Problems]
Graph Theory 1 [Programming Competition Problems]
WilliamFiset
26 Logic 1 [Programming Competition Problems]
Logic 1 [Programming Competition Problems]
WilliamFiset
27 Grid Problems 1 [Programming Competition Problems]
Grid Problems 1 [Programming Competition Problems]
WilliamFiset
28 Dynamic Programming 1 [Programming Competition Problems]
Dynamic Programming 1 [Programming Competition Problems]
WilliamFiset
29 Introduction to Big-O
Introduction to Big-O
WilliamFiset
30 Dynamic and Static Arrays
Dynamic and Static Arrays
WilliamFiset
31 Dynamic Array Code
Dynamic Array Code
WilliamFiset
32 Linked Lists Introduction
Linked Lists Introduction
WilliamFiset
33 Doubly Linked List Code
Doubly Linked List Code
WilliamFiset
34 Stack Introduction
Stack Introduction
WilliamFiset
35 Stack Implementation
Stack Implementation
WilliamFiset
36 Stack Code
Stack Code
WilliamFiset
37 Queue Introduction
Queue Introduction
WilliamFiset
38 Queue Implementation
Queue Implementation
WilliamFiset
39 Queue Code
Queue Code
WilliamFiset
40 Priority Queue Introduction
Priority Queue Introduction
WilliamFiset
41 Priority Queue Min Heaps and Max Heaps
Priority Queue Min Heaps and Max Heaps
WilliamFiset
42 Priority Queue Inserting Elements
Priority Queue Inserting Elements
WilliamFiset
43 Priority Queue Removing Elements
Priority Queue Removing Elements
WilliamFiset
44 Priority Queue Code
Priority Queue Code
WilliamFiset
45 Union Find Introduction
Union Find Introduction
WilliamFiset
46 Union Find Kruskal's Algorithm
Union Find Kruskal's Algorithm
WilliamFiset
47 Union Find - Union and Find Operations
Union Find - Union and Find Operations
WilliamFiset
48 Union Find Path Compression
Union Find Path Compression
WilliamFiset
49 Union Find Code
Union Find Code
WilliamFiset
50 Binary Search Tree Introduction
Binary Search Tree Introduction
WilliamFiset
51 Binary Search Tree Insertion
Binary Search Tree Insertion
WilliamFiset
52 Binary Search Tree Removal
Binary Search Tree Removal
WilliamFiset
53 Binary Search Tree Traversals
Binary Search Tree Traversals
WilliamFiset
54 Binary Search Tree Code
Binary Search Tree Code
WilliamFiset
55 Fenwick Tree range queries
Fenwick Tree range queries
WilliamFiset
56 Fenwick Tree point updates
Fenwick Tree point updates
WilliamFiset
57 Fenwick Tree construction
Fenwick Tree construction
WilliamFiset
58 Fenwick tree source code
Fenwick tree source code
WilliamFiset
59 Hash table hash function
Hash table hash function
WilliamFiset
60 Hash table separate chaining
Hash table separate chaining
WilliamFiset

This video teaches beginner tree algorithms, including calculating leaf node sum and binary tree height, using depth-first search and recursive functions. It provides pseudocode examples and explanations to help beginners understand the concepts.

Key Takeaways
  1. Define the problem to solve (leaf node sum or binary tree height)
  2. Choose a traversal method (depth-first search)
  3. Implement the algorithm using recursive functions
  4. Test and verify the results
💡 Recursive functions can be used to solve tree-related problems, such as calculating leaf node sum and binary tree height, by breaking down the problem into smaller sub-problems.

Related Reads

📰
The Minecraft anvil is a tree-cost optimization problem in disguise
Optimize tree costs in Minecraft using graph theory and algorithms, just like the anvil repair system
Dev.to · Mark
📰
KMP Algorithm (Knuth-Morris-Pratt): The Smart Way to Perform String Matching in O(N)
Learn the KMP algorithm for efficient string matching in O(N) time complexity and improve your coding skills
Dev.to · Jaspreet singh
📰
Every Backtracking Problem Is the Same Three Lines. I Just Couldn't See the Tree.
Master backtracking problems with a simple three-line approach to improve problem-solving skills in coding interviews and challenges
Dev.to · Alex Mateo
📰
DSA From Zero to Hero #3: Sliding Window (Fixed Size) Explained With a Java Example
Learn to solve subarray problems efficiently using the sliding window technique, a crucial skill for software engineers and data scientists
Medium · Programming

Chapters (6)

Intro
0:40 Problem 1: Leaf node sum
2:19 Problem 1: Pseudocode
3:32 Problem 2: Tree height
6:50 Problem 2: Pseudocode
8:25 Problem 2: Tree height simplification
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →