2023年12月26日 星期二

100. Same Tree

 100. Same Tree   ( https://leetcode.com/problems/same-tree/ )

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:
Input: p = [1,2,3], q = [1,2,3]
Output: true

Example 2:
Input: p = [1,2], q = [1,null,2]
Output: false

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

Constraints:
The number of nodes in both trees is in the range [0, 100].
-104 <= Node.val <= 104


思路
兩棵樹要一樣,代表著
中間節點的值一樣
左子樹一樣
右子樹一樣
然後 return 三個比較結果的 AND 值

所以要遞迴取得三者的比較結果
遞迴的終點條件就是樹葉節點
樹葉節點的特性是 NULL
所以兩棵樹只要有一個走到NULL
就是該位置走到樹葉了
若兩樹相同,就必須同為 NULL
若兩樹不同,就只有一者 NULL
所以遇到樹葉,就可直接比較兩個 pointer

/**
 * 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 == NULL || q == NULL)
        {
            return p == q;
        }

        bool sameLeft = isSameTree(p->left, q->left);
        bool sameRight = isSameTree(p->right, q->right);
        bool sameVal = p->val == q->val;
        return sameLeft && sameRight && sameVal;
    }
};



沒有留言:

張貼留言