Solved "Same Tree" problem on LeetCode using tree recursion

https://lnkd.in/gmysJzSq Today I solve the classic tree-recursion problem on LeetCode: “Same Tree”. The task was to determine if two binary trees are structurally identical and have the same node values. What I did Handled base cases: if both nodes are nullptr, return true; if one is nullptr and the other isn’t, return false. Recursively compared the left subtrees and right subtrees. Checked the current node values after the recursive calls. Ensured the solution is clean, simple, and efficient in terms of logic. Here’s the core solution snippet: /** * 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 { public: bool isSameTree(TreeNode* p, TreeNode* q) { if (p == nullptr && q == nullptr) return true; if (p == nullptr || q == nullptr) return false; bool leftSame = isSameTree(p->left, q->left); bool rightSame = isSameTree(p->right, q->right); return (p->val == q->val) && leftSame && rightSame; } }; Key Takeaways Recursive tree problems often boil down to base case checks + recursive calls on subtrees + combining results. Clean code is powerful: Fewer lines, clear logic, fewer errors (e.g., mis-using -> vs >). Regularly solving such problems builds strong fundamentals for more complex tree or graph challenges later on. #LeetCode #Cplusplus #TreeAlgorithm #DSA #ProblemSolving #CodingJourney #CleanCode #SoftwareEngineering

To view or add a comment, sign in

Explore content categories