🎃

LeetCode #100 Same Tree

2024/10/10に公開

問題概要

入力値:p(binary tree), q(binary tree)
出力値:boolean
return whether p and q are same
問題のリンク

入力例

arr1: [1,2,3]
arr2: [1,2,3]
result: true

解答例1

計算量:O(n)
Python

class Solution(object):
    def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        self.result = True
        def search(root1, root2):
            if not root1 and not root2:
                return
            elif not root1:
                self.result = False
                return
            elif not root2:
                self.result = False
                return
            if root1.val != root2.val:
                self.result = False
                return
            search(root1.right, root2.right)
            search(root1.left, root2.left)
        search(p, q)
        return self.result

Runtime: 16ms
Beats: 44.43%

C++

class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* 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);
        }
        return false;
    }
};

Runtime: 0ms
Beats: 100%

Discussion