Code – Inorder Traversal (Array)
class Solution {
public:
void vectorStore(vector<int> &store, TreeNode* root){
if(root == nullptr) {
return ;
vectorStore(store, root->left);
store.push_back(root->val);
vectorStore(store, root->right);
vector<int> inorderTraversal(TreeNode* root) {
vector<int> store;
vectorStore(store, root);
return store;
};
Code – Preorder Traversal
class Solution {
public:
void vectorStore(vector<int> &store, TreeNode* root){
if(root == nullptr) {
return ;
store.push_back(root->val);
vectorStore(store, root->left);
vectorStore(store, root->right);
vector<int> preorderTraversal(TreeNode* root) {
vector<int> store;
vectorStore(store, root);
return store;
};
Code – Depth of Binary
Tree
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == NULL)
return 0;
if (root->left == NULL && root->right == NULL)
return 1;
int l = INT_MAX, r = INT_MAX;
if (root->left)
l = minDepth(root->left);
if (root->right)
r = minDepth(root->right);
return min(l , r) + 1;
};
Code – Maximum Depth of
Binary Tree
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == NULL) {
return 0; // Base case: Empty tree
queue<TreeNode*> q;
q.push(root);
int depth = 0;
while (!q.empty()) {
int level_size = q.size();
depth++;
for (int i = 0; i < level_size; i++) {
TreeNode* node = q.front();
q.pop();
if (node->left) {
q.push(node->left);
if (node->right) {
q.push(node->right);
return depth;
};
Code – Path Sum in Binary
Tree
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if (root == nullptr)
return false;
if (root->val == sum && root->left == nullptr && root->right == nullptr)
return true;
return hasPathSum(root->left, sum - root->val) ||
hasPathSum(root->right, sum - root->val);
};