From 6a5cc5f178b964d17fd363f938326c41318881ad Mon Sep 17 00:00:00 2001 From: Chiayi Chiu Date: Wed, 13 Jul 2022 23:01:51 +0800 Subject: [PATCH] problem: 0100 same tree --- 0100 Same Tree/0100 Same Tree.md | 68 ++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 0100 Same Tree/0100 Same Tree.md diff --git a/0100 Same Tree/0100 Same Tree.md b/0100 Same Tree/0100 Same Tree.md new file mode 100644 index 0000000..f658069 --- /dev/null +++ b/0100 Same Tree/0100 Same Tree.md @@ -0,0 +1,68 @@ +# 0100. Same Tree + +* Difficulty: easy +* Link: https://leetcode.com/problems/same-tree/ +* Topics: DFS-BFS + +# Clarification + +1. Check the inputs and outputs + - INPUT: + - Optional[TreeNode] + - Optional[TreeNode] + - OUTPUT: + - boolean + +# Solution + +### Thought Process + +1. +- Implement + + ```python + # Definition for a binary tree node. + # class TreeNode: + # def __init__(self, val=0, left=None, right=None): + # self.val = val + # self.left = left + # self.right = right + class Solution: + def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: + def isSame(p,q): + if not p and not q: + return True + if not p or not q: + return False + if p.val != q.val: + return False + return True + + deq_p = collections.deque() + deq_q = collections.deque() + + deq_p.append(p) + deq_q.append(q) + + while deq_p and deq_q: + p = deq_p.popleft() + q = deq_q.popleft() + + if not isSame(p, q): + return False + + if p or q: + deq_p.append(p.left) + deq_p.append(p.right) + deq_q.append(q.left) + deq_q.append(q.right) + + return True + ``` + + +### Complexity + +- Time complexity: O(n) +- Space complexity: O(n) + - to keep a queue \ No newline at end of file