LeetCode-python 101. Symmetric binary tree
Difficulty: Simple Type: Binary Tree
Given a binary tree, check if it is mirror-symmetric.
For example, the binary tree [1,2,2,3,4,4,3] is symmetric.
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2, null, 3, null, 3] is not mirror-symmetric:
1
/ \
2 2
\ \
3 3
Problem-solving ideas
Turn this question into whether the left and right subtrees of the root node are mirror-symmetric
The conditions for the two trees to mirror each other are:
- Their root nodes have the same value
- The left subtree of each tree is mirror-symmetric to the right subtree of another tree
Code
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def convers(self,p,q): if p == None and q == None: return True elif p == None or q == None: return False elif p.val == q.val: return self.convers(p.left, q.right) and self.convers(p.right, q.left) else: return False def isSymmetric(self, root: TreeNode) -> bool: if root: return self.convers(root.left,root.right) else: return True
LeetCode-python 104. Maximum depth of binary tree
Difficulty: Simple Type: Binary tree, recursive
Given a binary tree, find its maximum depth.
The depth of the binary tree is the number of nodes on the longest path from the root node to the furthest leaf node.
Example
given a binary tree [3,9,20, null, null, 15,7]
3
/ \
9 20
/ \
15 7
Problem-solving ideas
The maximum depth is the greater of +1 in the depth of the left or right subtree, recursively looking in the subtree of the subtree
Code
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def maxDepth(self, root: TreeNode) -> int: if root is None: return 0 else: l = self.maxDepth(root.left) r = self.maxDepth(root.right) return max(l,r)+1