leetcode解题: Same Tree (100)

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.

解法1:递归 / 分治

经典的二叉树的问题,用递归很容易解决。两个树相等首先是root的值要一样,然后左子树相等,右子树相等。终结条件是如果值不一样或者有一个root为空另一个不是空则结构不同。

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* 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 == NULL && q != NULL) {
return false;
}
if (p != NULL && q == NULL) {
return false;
}
if (p == NULL && q == NULL) {
return true;
}
if (p-> val != q->val) {
return false;
}
bool left = isSameTree(p->left, q->left);
if (!left) return false;
bool right = isSameTree(p->right, q->right);
return right;
}
};

Java

1