判断两棵树是否相同,可以根据先序遍历和中序遍历或中序遍历及后序遍历是否一致来判断,也可以根据简单的递归方式来解决。
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 1:
Input: 1 1 / \ / \ 2 3 2 3 [1,2,3], [1,2,3] Output: trueExample 2:
Input: 1 1 / \ 2 2 [1,2], [1,null,2] Output: falseExample 3:
Input: 1 1 / \ / \ 2 1 1 2 [1,2,1], [1,1,2] Output: false
代码为:
/**
* 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 true;
if(p != NULL && q != NULL)
{
if(p->val == q->val)
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
return false;
}
};