0% found this document useful (0 votes)
13 views6 pages

Trees_Blind75

The document outlines 15 common binary tree problems and their solutions in C++, including Invert Binary Tree, Maximum Depth, Diameter, and others. Each problem is accompanied by a brief description, a code solution, and a note explaining the approach used. The solutions utilize various techniques such as recursion, depth-first search, breadth-first search, and tree traversal methods.

Uploaded by

leviandlight
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views6 pages

Trees_Blind75

The document outlines 15 common binary tree problems and their solutions in C++, including Invert Binary Tree, Maximum Depth, Diameter, and others. Each problem is accompanied by a brief description, a code solution, and a note explaining the approach used. The solutions utilize various techniques such as recursion, depth-first search, breadth-first search, and tree traversal methods.

Uploaded by

leviandlight
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Linked List - Blind 75 (C++)

1. Invert Binary Tree


Problem: Invert a binary tree (mirror image).
Solution:

TreeNode* invertTree(TreeNode* root) {


if (!root) return nullptr;
TreeNode* left = invertTree(root->left);
TreeNode* right = invertTree(root->right);
root->left = right;
root->right = left;
return root;
}
Note: Recursively swap left and right subtrees.

2. Maximum Depth of Binary Tree


Problem: Find the maximum depth (height) of a binary tree.
Solution:

int maxDepth(TreeNode* root) {


if (!root) return 0;
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
Note: Recursive DFS approach.

3. Diameter of Binary Tree


Problem: Find the length of the longest path between any two nodes.
Solution:

int diameterOfBinaryTree(TreeNode* root) {


int diameter = 0;
height(root, diameter);
return diameter;
}
int height(TreeNode* node, int& diameter) {
if (!node) return 0;
int left = height(node->left, diameter);
int right = height(node->right, diameter);
diameter = max(diameter, left + right);
return 1 + max(left, right);
}
Note: Diameter is updated during height calculation.

4. Balanced Binary Tree


Problem: Check if tree is height-balanced (no two leaves differ in depth by >1).
Solution:

bool isBalanced(TreeNode* root) {


return checkHeight(root) != -1;
}
int checkHeight(TreeNode* node) {
if (!node) return 0;
int left = checkHeight(node->left);
if (left == -1) return -1;
int right = checkHeight(node->right);
if (right == -1) return -1;
if (abs(left - right) > 1) return -1;
return 1 + max(left, right);
}
Note: Modified height calculation that checks balance.

5. Same Tree
Problem: Check if two binary trees are identical.
Solution:

bool isSameTree(TreeNode* p, TreeNode* q) {


if (!p || !q) return p == q;
return p->val == q->val &&
isSameTree(p->left, q->left) &&
isSameTree(p->right, q->right);
}
Note: Recursive comparison of structure and values.

6. Subtree of Another Tree


Problem: Check if one tree is a subtree of another.
Solution:

bool isSubtree(TreeNode* root, TreeNode* subRoot) {


if (!root) return false;
return isSameTree(root, subRoot) ||
isSubtree(root->left, subRoot) ||
isSubtree(root->right, subRoot);
}
Note: Uses isSameTree as helper function.

7. Lowest Common Ancestor of a Binary Search Tree


Problem: Find the lowest common ancestor of two nodes in a BST.
Solution:

TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {


if (p->val < root->val && q->val < root->val)
return lowestCommonAncestor(root->left, p, q);
if (p->val > root->val && q->val > root->val)
return lowestCommonAncestor(root->right, p, q);
return root;
}
Note: Leverages BST property for efficient search.

8. Binary Tree Level Order Traversal


Problem: Return level-order traversal as list of lists.
Solution:

vector<vector<int>> levelOrder(TreeNode* root) {


vector<vector<int>> result;
queue<TreeNode*> q;
if (root) q.push(root);
while (!q.empty()) {
int size = q.size();
vector<int> level;
while (size--) {
TreeNode* node = q.front(); q.pop();
level.push_back(node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
result.push_back(level);
}
return result;
}
Note: Standard BFS using queue.

9. Binary Tree Right Side View


Problem: Return nodes visible from the right side.
Solution:

vector<int> rightSideView(TreeNode* root) {


vector<int> result;
queue<TreeNode*> q;
if (root) q.push(root);
while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
TreeNode* node = q.front(); q.pop();
if (i == size-1) result.push_back(node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
return result;
}
Note: Modified level-order traversal taking last node at each level.

10. Count Good Nodes In Binary Tree


Problem: Count nodes where path from root has no greater value.
Solution:

int goodNodes(TreeNode* root, int max_val = INT_MIN) {


if (!root) return 0;
int count = root->val >= max_val;
max_val = max(max_val, root->val);
return count + goodNodes(root->left, max_val) + goodNodes(root->right,
max_val);
}
Note: Track maximum value along current path.

11. Validate Binary Search Tree


Problem: Check if tree is a valid BST.
Solution:

bool isValidBST(TreeNode* root) {


return validate(root, nullptr, nullptr);
}
bool validate(TreeNode* node, TreeNode* min, TreeNode* max) {
if (!node) return true;
if ((min && node->val <= min->val) || (max && node->val >= max->val))
return false;
return validate(node->left, min, node) && validate(node->right, node, max);
}
Note: Track valid range for each subtree.

12. Kth Smallest Element In a BST


Problem: Find the kth smallest element in a BST.
Solution:

int kthSmallest(TreeNode* root, int k) {


stack<TreeNode*> st;
while (true) {
while (root) {
st.push(root);
root = root->left;
}
root = st.top(); st.pop();
if (--k == 0) return root->val;
root = root->right;
}
}
Note: In-order traversal with early termination.

13. Construct Binary Tree From Preorder And Inorder Traversal


Problem: Build tree from preorder and inorder traversal arrays.
Solution:

TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {


unordered_map<int, int> in_map;
for (int i = 0; i < inorder.size(); i++)
in_map[inorder[i]] = i;
int pre_idx = 0;
return build(preorder, in_map, pre_idx, 0, inorder.size()-1);
}
TreeNode* build(vector<int>& preorder, unordered_map<int, int>& in_map, int&
pre_idx, int in_left, int in_right) {
if (in_left > in_right) return nullptr;
TreeNode* root = new TreeNode(preorder[pre_idx++]);
int in_idx = in_map[root->val];
root->left = build(preorder, in_map, pre_idx, in_left, in_idx-1);
root->right = build(preorder, in_map, pre_idx, in_idx+1, in_right);
return root;
}
Note: Recursive construction using inorder positions.

14. Binary Tree Maximum Path Sum


Problem: Find maximum path sum where path can be any node sequence.
Solution:

int maxPathSum(TreeNode* root) {


int max_sum = INT_MIN;
pathSum(root, max_sum);
return max_sum;
}
int pathSum(TreeNode* node, int& max_sum) {
if (!node) return 0;
int left = max(0, pathSum(node->left, max_sum));
int right = max(0, pathSum(node->right, max_sum));
max_sum = max(max_sum, left + right + node->val);
return max(left, right) + node->val;
}
Note: Post-order traversal tracking local and global maxima.

15. Serialize And Deserialize Binary Tree


Problem: Convert tree to string and reconstruct from string.
Solution:

string serialize(TreeNode* root) {


ostringstream out;
serialize(root, out);
return out.str();
}
void serialize(TreeNode* node, ostringstream& out) {
if (!node) {
out << "# ";
return;
}
out << node->val << " ";
serialize(node->left, out);
serialize(node->right, out);
}

TreeNode* deserialize(istringstream& in) {


string val;
in >> val;
if (val == "#") return nullptr;
TreeNode* node = new TreeNode(stoi(val));
node->left = deserialize(in);
node->right = deserialize(in);
return node;
}
Note: Pre-order traversal with null markers.

You might also like