Valid Anagrams - Leet Code Solution
Problem Statement Given two strings s and t , write a function to determine if t…
November 19, 2020
Given a Binary tree, print out nodes in level order traversal from left to right.
50
/ \
80 30
/ \ \
20 40 10
# Output
# 50 80 30 20 40 10
Use BFS (Breadth First Search) algorithm. Since, it reaches out to nodes first that are immediate neighbours.
Idea is to take a queue, keep accumulating queue for each child.
void bfs(Node node) {
Queue<Node> q = new Queue();
q.add(node);
while (!q.isEmpty()) {
Node n = q.pop();
print(n);
if (n.left != null) q.add(n.left);
if (n.right != null) q.add(n.right);
}
}
The Complexity
is O(n)
as we are visiting each nodes only once.
You can prepare a list of nodes at each level. We will also use DFS (Depth First Search) algorithm here.
void levelOrder(Node node, List<List<Node>> list, int level) {
if (node == null)
return;
List<Node> levelList = list.get(level);
if (levelList == null) {
levelList = new ArrayList();
list.add(levelList);
}
levelList.add(node);
levelOrder(node.left, list, level+1);
levelOrder(node.right, list, level+1);
}
List<List<Node>> list = new ArrayList();
levelOrder(root, list, 0);
After this, we can print the list.
The Complexity
is O(n)
as we are visiting each nodes only once.
Problem Statement Given two strings s and t , write a function to determine if t…
Its a tree based data structure which is a complete binary tree(all nodes have…
Problem Statement Write a function that reverses a string. The input string is…
Problem Statement Given an array, rotate the array to the right by k steps…
Problem Statement There are two sorted arrays nums1 and nums2 of size m and n…
Problem Statement You are given an array of integers. And, you have find the…
Introduction Strapi is a backend system provides basic crud operations with…
Introduction I had to create many repositories in an Github organization. I…
Introduction I was trying to download some youtube videos for my kids. As I have…
Introduction In this post, we will explore some useful command line options for…
Introduction In this post, we will see how we can apply a patch to Python and…
Introduction We will introduce a Package Manager for Windows: . In automations…