Leetcode same tree 100. The problem-solving ideas and implemented in C ++

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/gjh13/article/details/90737664

Problem-solving ideas:

This question method uses recursive.

  1. Prior to the current node p and q be determined non-null, null if both, return true;

  2. If a is null, another non-null, then return false;

  3. pq are non-null, then compare their val, val if not equal, false;

  4. If equal to val, which recursively determines the left and right child nodes are the same.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if(!p && !q) return true;
        else if(!p && q || p && !q) return false;
        else if(p->val != q->val) return false;
        else{
            return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
        }
    }
};

 

 

Guess you like

Origin blog.csdn.net/gjh13/article/details/90737664