Sobes.tech
Junior — Senior

Simplification of the function comparing two binary trees

livecode

Task condition

The implementation of the isSameTree function is presented, which uses nested conditional operators. It is necessary to make the code more concise and understandable by removing unnecessary nesting, while maintaining correct recursive verification of the identity of two binary trees.

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) {}
};

bool isSameTree(TreeNode* node1, TreeNode* node2) {
    if (!node1 && !node2)
        return true;
    if (node1 && node2) {
        if (node1->val == node2->val) {
            if (isSameTree(node1->left, node2->left)) {
                return isSameTree(node1->right, node2->right);
            }
        }
    }
    return false;
}