【LeetCode-树】相同的树

题目描述

给定两个二叉树,编写一个函数来检验它们是否相同。
如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
示例:

输入:       1         1
          / \       / \
         2   3     2   3

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

输出: true

输入:      1          1
          /           \
         2             2

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

输出: false

题目链接: https://leetcode-cn.com/problems/same-tree/

思路

使用递归来做。代码如下:

/**
 * 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) {
        return compare(p, q);
    }

    bool compare(TreeNode* p, TreeNode* q){
        if(p==nullptr && q==nullptr) return true;
        if(p==nullptr || q==nullptr) return false;
        if(p->val!=q->val) return false;

        return compare(p->left, q->left) && compare(p->right, q->right);
    }
};
  • 时间复杂度:O(n)
    n 为节点个数。
  • 空间复杂度:O(h)
    h 为树高。

猜你喜欢

转载自www.cnblogs.com/flix/p/13170845.html