题目链接:Same Tree

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

这道题的要求是判断两棵树是否相同。两个二叉树相同定义为结构相同而且每个节点上的数字也都相同。

采用递归的思路,非常简单,就是判断两个节点的数字是否相同以及不断递归分别判断左右子树是否相同。

时间复杂度:O(n)

空间复杂度:O(1)

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
    bool isSameTree(TreeNode *p, TreeNode *q)
    {
        if(p != NULL && q != NULL)
            return p-> val == q -> val 
                && isSameTree(p -> left, q -> left) 
                && isSameTree(p -> right, q -> right);
        else
            return p == NULL && q == NULL;
    }
};

100道题了,mark一下,再接再厉,加油。

PS:这道题本应是2015-03-10做的,为了按顺序排序,所以将日期改为2015-03-11。