# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = None# class Solution(object):# def isSameTree(self, p, q):# """# :type p: TreeNode# :type q: TreeNode# :rtype: bool# """# if p is None and q is None:# return True# if p is None or q is None:# return Falsereturnp.val==q.valand \
self.isSameTree(p.left,q.left)and \
self.isSameTree(p.right,q.right)
572. Subtree of Another Tree (easy)
简述:判断t是否为s的子树(相同也算子树)
思路:构造isSame()辅助
联系:出自100
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# class Solution(object):# def isSubtree(self, s, t):# """# :type s: TreeNode# :type t: TreeNode# :rtype: bool# """# if s is None:# return Falsereturnself.isSame(s,t)orself.isSubtree(s.left,t)orself.isSubtree(s.right,t)# def isSame(self, s, t):# if s is None and t is None:# return True# if s is None or t is None:# return False# return s.val == t.val and \# self.isSame(s.left, t.left) and \# self.isSame(s.right, t.right)
101. Symmetric Tree (easy)
简述:判断二叉树是否对称
思路:改造为判断两棵树是否对称
联系:出自100
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# class Solution(object):# def isSymmetric(self, root):# """# :type root: TreeNode# :rtype: bool# """# if root is None:# return True# return self._isSymmetric(root.left, root.right)# 要点1-1: 下划线命名helper函数,添加参数def_isSymmetric(self,r1,r2):# if r1 is None and r2 is None:# return True# if r1 is None or r2 is None:# return False# return r1.val == r2.val and \# self._isSymmetric(r1.left, r2.right) and \# self._isSymmetric(r1.right, r2.left)
# class Solution(object):# def closestValue(self, root, target):# """# :type root: TreeNode# :type target: float# :rtype: int# """# if root.left is None and root.right is None:# return root.val# if target == root.val:# return root.val# if target > root.val:# if root.right is None:# return root.val# tmp_res = self.closestValue(root.right, target)ifabs(root.val-target)<=abs(tmp_res-target):# return root.val# else:# return tmp_res# else:# if root.left is None:# return root.val# tmp_res = self.closestValue(root.left, target)ifabs(root.val-target)<=abs(tmp_res-target):# return root.val# else:# return tmp_res
104. Maximum Depth of Binary Tree (easy)
简述:求二叉树最大深度, 通常定义如下 (此题按节点数量算深度)
I learned that depth and height are properties of a node:
The depth of a node is the number of edges from the node to the tree’s root node.
A root node will have a depth of 0.
The height of a node is the number of edges on the longest path from the node to a leaf.
A leaf node will have a height of 0.
Properties of a tree:
The height of a tree would be the height of its root node,
or equivalently, the depth of its deepest node.
The diameter (or width) of a tree is the number of nodes on the longest path between any two leaf nodes. The tree below has a diameter of 6 nodes.
depth往根(上)数,height往最远的叶(下)数,height等于maxDepth
思路:分治法,也可以遍历法
联系:出自100
1
2
3
4
5
6
7
8
9
# class Solution(object):# def maxDepth(self, root):# """# :type root: TreeNode# :rtype: int# """# if root is None:# return 0# return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
111. Minimum Depth of Binary Tree (easy)
简述:求二叉树最小深度
思路:分治法
联系:出自104
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# class Solution(object):# def minDepth(self, root):# """# :type root: TreeNode# :rtype: int# """# if root is None:# return 0ifroot.leftisNoneandroot.rightisNone:return1ifroot.leftisNone:returnself.minDepth(root.right)+1ifroot.rightisNone:returnself.minDepth(root.left)+1# return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
226. Invert Binary Tree (easy)
简述:左右反转二叉树
思路:分治
联系:出自100
1
2
3
4
5
6
7
8
9
10
11
12
# class Solution(object):# def invertTree(self, root):# """# :type root: TreeNode# :rtype: TreeNode# """# if root is None:# return None# if root.left is None and root.right is None:# return rootroot.left,root.right=self.invertTree(root.right),self.invertTree(root.left)# return root
669. Trim a Binary Search Tree (easy)
简述:裁剪BST,使得裁剪后元素位于区间[L, R](R>=L)内
思路:根节点三种情况:<L, >R, LR之间
联系:出自100
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# class Solution(object):# def trimBST(self, root, L, R):# """# :type root: TreeNode# :type L: int# :type R: int# :rtype: TreeNode# """# if root is None:# return None# if root.val < L:# return self.trimBST(root.right, L, R)# if root.val > R:# return self.trimBST(root.left, L, R)root.left,root.right=self.trimBST(root.left,L,R),self.trimBST(root.right,L,R)# return root
# class Solution(object):# def maxPathSum(self, root):# """# :type root: TreeNode# :rtype: int# """# 要点1-1: python最小整数self.res=-sys.maxsize-1# self.maxSumFromRoot(root)# return self.res# def maxSumFromRoot(self, root):# if root is None:# return 0# if root.left is None and root.right is None:# self.res = max(self.res, root.val)# return root.val# left_max = self.maxSumFromRoot(root.left)# right_max = self.maxSumFromRoot(root.right)self.res=max(self.res,root.val+ \
max(0,left_max,right_max,left_max+right_max))# return max(root.val, root.val + left_max, root.val + right_max)
257. Binary Tree Paths (easy)
简述:打印二叉树所有根到叶路径
思路:分治
联系:出自100
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# class Solution(object):# def binaryTreePaths(self, root):# """# :type root: TreeNode# :rtype: List[str]# """# if root is None:# return []# if root.left is None and root.right is None:# return [str(root.val)]# left_paths = self.binaryTreePaths(root.left)# right_paths = self.binaryTreePaths(root.right)# res = []# res += [str(root.val) + '->' + p for p in left_paths]# res += [str(root.val) + '->' + p for p in right_paths]# return res
# class Solution(object):# def findLeaves(self, root):# """# :type root: TreeNode# :rtype: List[List[int]]# """# 要点2-1: 全局变量,映射height_memo=dict()# self.label_height(root, height_memo)# # 要点2-2: 反向索引inverted indexreturnself.convert_memo(height_memo)# def label_height(self, root, height_memo):# if root is None:# return 0# if root.left is None and root.right is None:# height_memo[root] = 1# return 1# left_height = self.label_height(root.left, height_memo)# right_height = self.label_height(root.right, height_memo)# res_height = max(left_height, right_height) + 1# height_memo[root] = res_height# return res_height# def convert_memo(self, height_memo):# res = dict()# for k, v in height_memo.items():# if v not in res:# res[v] = list()# res[v].append(k.val)# ans = []# for i in range(len(res.keys())):# ans.append(res[i + 1])# return ans
617. Merge Two Binary Trees (easy)
简述:合并两棵二叉树,合并后节点为两棵对应节点之和
思路:分治
联系:出自669
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# class Solution(object):# def mergeTrees(self, t1, t2):# """# :type t1: TreeNode# :type t2: TreeNode# :rtype: TreeNode# """# if t1 is None:# return t2# if t2 is None:# return t1# root = TreeNode(t1.val + t2.val)# root.left = self.mergeTrees(t1.left, t2.left)# root.right = self.mergeTrees(t1.right, t2.right)# return root
1490. Clone N-ary Tree (medium)
简述:深拷贝N元树
思路:递归定义,分治
联系:出自100
1
2
3
4
5
6
7
8
9
10
11
12
# class Solution(object):# def cloneTree(self, root):# """# :type root: Node# :rtype: Node# """# if root is None:# return None# root_copy = Node(val=root.val)# for el in root.children:# root_copy.children.append(self.cloneTree(el))# return root_copy
# class Solution(object):# 要点1-1: 三种情况:1)两个节点都在树中返回lca, 2)一个在树中返回该节点,3)两个都不在返回NonedeflowestCommonAncestor(self,root,p,q):# """# :type root: TreeNode# :type p: TreeNode# :type q: TreeNode# :rtype: TreeNode# """# if root is None:# return None# if root == p or root == q:# return root# left_lca = self.lowestCommonAncestor(root.left, p, q)# right_lca = self.lowestCommonAncestor(root.right, p, q)# if left_lca and right_lca:# return root# if left_lca:# return left_lca# if right_lca:# return right_lca# return None
235. Lowest Common Ancestor of a Binary Search Tree (easy)
简述:求两节点在BST里的LCA(假设两节点都在树中)
思路:分治,根据情况走一边子树
联系:出自236
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# class Solution(object):# def lowestCommonAncestor(self, root, p, q):# """# :type root: TreeNode# :type p: TreeNode# :type q: TreeNode# :rtype: TreeNode# """# if root is None:# return None# if root == p or root == q:# return root# if p.val < root.val < q.val or q.val < root.val < p.val:# return root# if root.val < p.val:# return self.lowestCommonAncestor(root.right, p, q)# else:# return self.lowestCommonAncestor(root.left, p, q)
156. Binary Tree Upside Down (medium)
简述:上下翻转二叉树,所给二叉树的性质:右节点是空或是有兄弟节点的叶节点
思路:画图按例子翻转
联系:出自226
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# class Solution(object):# def upsideDownBinaryTree(self, root):# """# :type root: TreeNode# :rtype: TreeNode# """# if root is None:# return None# if root.left is None and root.right is None:# return root# res = self.upsideDownBinaryTree(root.left)root.left.left,root.left.right=root.right,root# root.left, root.right = None, None# return res