Skip to main content

Posts

Showing posts from April, 2020

valarray class in C++

Valarray is a class similar to vector but is efficient than vector if it comes to mathematical operations. It provides many element-wise operations, various forms of generalized subscript operators, slicing and indirect access. In some mathematical operations, valarrays are more efficient than vector operations. Some of the APIs provided by valarray class are: apply(the function that performs the operation on every element) This API applies manipulation on the given arguments to all the array elements. valarray<int> arr = {1,2,3,4,5,6}; arr.apply([] (int x){return x = x+ 5;}); The above code increments every element by 5 sum() This API performs the sum of all elements in the given array valarray<int> arr = {1,2,3,4,5}; arr.sum(); The above code sums up all the elements of the array which is 15. min() This API finds out the smallest element in the array. max() This API finds out the largest element in the array. valarray<int> arr = {1,2,...

STL APIs in C++

Here is the most used of the many functions that STL provides:   sort(first_iterator, last_iterator)           - It sorts the elements in ascending order by default. To sort it in descending order we have to pass comparison function as the third parameter. greater<int>() can be used to achieve that purpose. reverse(first_iterator, last_iterator)          - It reverses the vector *max_element(first_iterator, last_iterator)          - It returns the maximum element of the vector *min_element(first_iterator, last_iterator)          - It returns the minimum element of the vector accumulate(first_iterator, last_iterator, initial sum value)          - It returns the sum of the elements plus the initial sum value count(first_iterator, last_iterator, element)         - It returns the number o...

Leet Code Problem #114. Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place. For example, given the following tree: 1 / \ 2 5 / \ \ 3 4 6 The flattened tree should look like: 1 \ 2 \ 3 \ 4 \ 5 \ 6 Approach to the solution: Traverse the left sub tree until the left most leaf found recursively. Store the right child in temp variable. Take that left node and make it as right child of leaf parent. Now traverse through the right child of the parent until the leaf node is found. Assign its right child as temp. Do the same thing for right sub tree as well. Solution in C++:   /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void flatten(TreeNode* root) { cal(root); } void cal(TreeNode* root){ if(!root) re...