Same Tree Leet Code Solution in C++

Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.

Constraints:

  • The number of nodes in the tree is in the range [1, 1000].
  • -100 <= Node.val <= 100
Input: p = [1,2,3], q = [1,2,3]
Output: true

@abhishekx20 author
/**
 * 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 both trees are empty, return true
    if (!p && !q) return true;
    // If one tree is empty and the other is not, return false
    if (!p || !q) return false;
    // If the values of the root nodes are not equal, return false
    if (p->val != q->val) return false;
    // Recursively check the left and right subtrees
    return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
};

How to Create a flex box in Html | Pythongdb

Leave a Comment