Open fockspaces opened 1 year ago
recursion + 做個NULL判斷
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(!p || !q) return p == q;
return p->val == q->val
&& isSameTree(p->left, q->left)
&& isSameTree(p->right, q->right);
}
};
var isSameTree = function(p, q) {
//如果兩棵樹都是空的時候
if(p == null && q == null){
return true;
}
//如果兩棵樹有其中一棵是空的時候
if(p == null || q == null){
return false;
}
//比較兩個樹在同一節點上的值是否相等
if(p.val == q.val){
//如果相等就繼續比,比到結束
return isSameTree(p.left,q.left) && isSameTree(p.right, q.right);
}else{
//如果不相等就回傳錯誤
return false;
}
};
Given the roots of two binary trees p and q, 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:![image](https://github.com/ZhongKuo0228/study/assets/63909491/1e9712ce-537d-459f-bf17-8a626f6d0355)
Input: p = [1,2,3], q = [1,2,3] Output: true