Day 1 (30 Days of Code)

Day 1 (30 Days of Code)

30 June 2023

For the whole day, I only did DSA. At first, I reviewed the theoretical portion of Binary Trees. Then I did several questions related to the binary tree that is given in my DSA course module. After that, I did 2 easy questions in Leetcode for more practice.

What did I learn?

Most of the questions related to binary can easily be done through a recursive approach which is DFS. However, some questions can only be done through BFS.

  1. Binary Tree Paths

    My Solution:
class Solution {
public:

    void helper(TreeNode* root,string path,vector<string>* output){

        if(root==NULL){
            return;
        }
        path += to_string(root->val);
        if(root->left==NULL && root->right==NULL){
            output->push_back(path);

            return;
        }
        path+="->";

        helper(root->left, path, output);
        helper(root->right, path, output);

    }
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string>* output = new vector<string>();

        helper(root,"",output);

        vector<string> answer;

        for(int i=0;i<output->size();i++){
            answer.push_back(output->at(i));
        }
        return answer;
    }
};
  1. Binary Tree Tilt

    My Solution:
class Solution {
public:
    int sumOfNodes(TreeNode* root){
        if(root==NULL){
            return 0;
        }
        return sumOfNodes(root->left)+sumOfNodes(root->right)+root->val;
    }
    int findTilt(TreeNode* root) {
        if(root==NULL){
            return 0;
        }

        int leftSum = sumOfNodes(root->left);
        int rightSum = sumOfNodes(root->right);

        root->val = max(leftSum,rightSum)-min(leftSum,rightSum);

        int leftTilt = findTilt(root->left);
        int  rightTilt = findTilt(root->right);

        return leftTilt+rightTilt+root->val;
    }
};

Screenshots

Screenshot