-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path101.symmetric-tree.py
61 lines (49 loc) · 1.56 KB
/
101.symmetric-tree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#
# @lc app=leetcode id=101 lang=python3
#
# [101] Symmetric Tree
#
# @lc code=start
# 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 isSymmetric(self, root: Optional[TreeNode]) -> bool:
def dfs(left_node, right_node):
if not left_node and not right_node:
return True
if not left_node or not right_node:
return False
if left_node.val != right_node.val:
return False
return dfs(left_node.left, right_node.right) and dfs(left_node.right, right_node.left)
return dfs(root, root)
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
"""
Iterative DFS approach
Using Stack
T: O(V+E) 36.80% | 53ms
S: O(L) 93.90% | 13.9mb
"""
if root is None:
return True
stack = [(root.left, root.right)]
while stack:
left, right = stack.pop()
# Check
if left is None and right is None:
continue
# Check
if left is None or right is None:
return False
# Check
if left.val != right.val:
return False
# Appending
stack.append((left.left, right.right))
stack.append((left.right, right.left))
return True
# @lc code=end