Problems
July 14, 2022
Diameter of binary tree
We can calculate the depth of a subtree with DFS. Then we add both subtree and store it in our running answer. After the whole tree traversal is done, we return our running answer. Time...
ReadJuly 14, 2022
Invert binary tree
We can take the left subtree and right subtree and swap their position. We will do it recursively for every subtree.
Time Complexity: O(n)
Space Complexity: O(n)
July 14, 2022
Maximum depth of binary tree
We will traverse the tree with DFS and keep a counter to keep track of every level. Then we will take the maximum from both subtree and return the counter.
Time Complexity: O(n)
...
July 14, 2022
Maximum depth of n-ary tree
We will traverse the tree with DFS and keep a counter to keep track of every level. Then we will take the maximum from all of those level and return the counter.
Time Complexity: O(n)
...
July 14, 2022
Same tree
We can traverse through the whole tree and compare each value. We are doing it with DFS for this solution.
We are traversing the thee once, so time complexity is O(n)
. The call stack...
July 14, 2022
Subtree of another tree
We can check whether two tree are same using the same logic from Same tree problem. Then we will check recursively for every subtree whether that is same as out target subtree. Time Complexity:...
ReadJuly 14, 2022
Two sum II - input array is sorted
As the array is sorted, we will take 2 pointer at the beginning and the end. If the sum of two numbers are equal to target, we return. If the sum is bigger than target, that means we need a smaller...
ReadJuly 13, 2022
Binary tree level order traversal
This is a classing BFS problem. We should traverse the whole tree with BFS, and store the values level by level to a list. Then combine each level to a list and return. This is very efficient....
ReadJuly 13, 2022
Number of 1 bits
We can logical and any number with 1 to check whether the last bit of that number is 1 or 0. We can also check this by checking the number is odd or even. Odd numbers always has last bit as 1. We...
ReadJuly 13, 2022
Product of array except self
We can go thorugh the whole list once and caculate and store the multiplicatio of prefix indeies in the result array directly. That way we don't use any extra memory. Then we do the same thing but in...
Read