ZhongKuo0228 / study

0 stars 0 forks source link

100. Same Tree #9

Open fockspaces opened 1 year ago

fockspaces commented 1 year ago

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

Input: p = [1,2,3], q = [1,2,3] Output: true

fockspaces commented 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);
    }
};
ZhongKuo0228 commented 1 year ago
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;
    }

};