题目链接: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 class Solution {
 2 public:
 3     bool isSameTree(TreeNode *p, TreeNode *q)
 4     {
 5         if(p != NULL && q != NULL)
 6             return p-> val == q -> val 
 7                 && isSameTree(p -> left, q -> left) 
 8                 && isSameTree(p -> right, q -> right);
 9         else
10             return p == NULL && q == NULL;
11     }
12 };

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

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