Same Tree
Leetcode algorithms problem 100: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.問題提示
無
思路
使用遞歸,首先返回節點爲NULL時的相等情況;兩個節點都是有效指針時,如果根值不一樣,返回false,一樣則進入遞歸:根的左側樹是相同的(遞歸)&&根的右側樹是相同的(遞歸),否則返回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 (p == q);
}else {
if(p->val != q->val){
return false;
}else{
return (isSameTree(p->left,q->left)&&isSameTree(p->right,q->right));
}
}
}
};
時間複雜度: O(n)
空間複雜度: O(2^n)