Skip to main content

Posts

Showing posts from June, 2020

Tree Data Structure related must solve programming questions: Part - 2

Problem Statement: Given a tree return inorder traversal of a binary tree. Note: Solve it using both recursion and iterative approach. Approach - 1(Recursive approach): Recursive approach is very simple. Inorder traversal is traversing left sub tree first Then visiting root and finally visiting right sub tree. Break the recursion whenever there is no node available. Code in C++: class Solution {         void traverse(TreeNode* node, vector<int> &res){             if(!node)                 return;             traverse(node->left, res);                        res.push_back(node->val);           ...

Tree Data Structure related must solve programming questions: Part - 1

LeetCode Problem #687 Given a binary tree find the longest possible path with same node values. The length of the path is determined the number of edges between the node. Example 1: Input: 5 / \ 4 5 / \ \ 1 1 5 Output:  2   Example 2: Input: 1 / \ 4 5 / \ \ 4 4 5 Output:  2 Solution in C++: /**  * Definition for a binary tree node.  * struct TreeNode {  *     int val;  *     TreeNode *left;  *     TreeNode *right;  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}  * };  */ class Solution ...