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&&q)||(!q&&p)) return false; if(!p&&!q) return true; return (p->val==q->val&&isSameTree(p->left,q->left)&&isSameTree(p->right,q->right)); } };