美文网首页
100. Same Tree

100. Same Tree

作者: SilentDawn | 来源:发表于2018-06-13 22:12 被阅读0次

Problem

Given two binary trees, 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.

Example

Input:     1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

Output: true
Input:     1         1
          /           \
         2             2

        [1,2],     [1,null,2]

Output: false
Input:     1         1
          / \       / \
         2   1     1   2

        [1,2,1],   [1,1,2]

Output: false

Code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
static int var = [](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();
class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if(p==NULL && q==NULL)
            return true;
        else if(p!=NULL && q!=NULL && p->val==q->val)
            return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
        else
            return false;
    }
};

Result

100. Same Tree.png

相关文章

网友评论

      本文标题:100. Same Tree

      本文链接:https://www.haomeiwen.com/subject/cdiseftx.html