计算二叉树有多少个节点
def count(root):
if not root:
return 0
return 1 + count(root.left) + count(root.right)
计算二叉树的深度
def count_depth(root):
if not root:
return 0
return max(count_depth(root.left), count_depth(root.right)) + 1
226. 翻转二叉树
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if not root:
return None
root.left, root.right = root.right, root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
114. 二叉树展开为链表
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
if not root:
return None
self.flatten(root.left)
self.flatten(root.right)
left = root.left
right = root.right
root.left = None
root.right = left
p = root
while p.right:
p = p.right
p.right = right
return root
116. 填充每个节点的下一个右侧节点指针
class Solution:
def connect(self, root: 'Node') -> 'Node':
if not root:
return None
self.connectTwoNode(root.left, root.right)
return root
def connectTwoNode(self, node1, node2):
if (not node1) or (not node2):
return
node1.next = node2
self.connectTwoNode(node1.left, node1.right)
self.connectTwoNode(node2.left, node2.right)
self.connectTwoNode(node1.right, node1.left)
654. 最大二叉树
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
m = max(nums)
ind = nums.index(m)
l = nums[:ind]
r = nums[ind+1:]
t = TreeNode(m)
t.left = self.constructMaximumBinaryTree(l) if l else None
t.right = self.constructMaximumBinaryTree(r) if r else None
return t
105. 从前序与中序遍历序列构造二叉树
class Solution(object):
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
#先序遍历的列表为[根,左,右],中序遍历的列表为[左,根,右],则中序遍历中根的下标为先序遍历中左的边界
if not preorder:
return None
root = TreeNode(preorder[0])
#找到根节点在中序遍历中的下标
n = inorder.index(root.val)
root.left = self.buildTree(preorder[1:n+1],inorder[:n])
root.right = self.buildTree(preorder[n+1:],inorder[n+1:])
return root
106. 从中序与后序遍历序列构造二叉树
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
if not postorder:
return None
root = TreeNode(postorder[-1])
n = inorder.index(root.val)
root.left = self.buildTree(inorder[:n],postorder[:n])
root.right = self.buildTree(inorder[n+1:],postorder[n:-1])
return root
652. 寻找重复的子树
class Solution:
def findDuplicateSubtrees(self, root: TreeNode) -> List[TreeNode]:
res = []
from collections import defaultdict
memo = defaultdict(int)
def traverse(root):
if not root:
return "#"
left = traverse(root.left)
right = traverse(root.right)
subTree = "{},{},{}".format(left, right, root.val)
memo[subTree] += 1
if memo[subTree] == 2:
res.append(root)
return subTree
traverse(root)
return res
236. 二叉树的最近公共祖先
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root:
return None
if root == p or root == q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left is not None and right is not None:
return root
if left is None and right is None:
return None
return right if left is None else left
110. 平衡二叉树
#自顶向下:
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def height(root: TreeNode) -> int:
if not root:
return 0
return max(height(root.left), height(root.right)) + 1
if not root:
return True
return abs(height(root.left) - height(root.right)) <= 1 and self.isBalanced(root.left) and self.isBalanced(root.right)
#自底向上
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def height(root):
if not root:
return 0
left = height(root.left)
right = height(root.right)
if left == -1 or right == -1 or abs(left - right) >= 2:
return -1
else:
return max(left, right) + 1
res = height(root)
return res >=0
589. N叉树的前序遍历
class Solution:
def __init__(self):
self.res = []
def preorder(self, root: 'Node') -> List[int]:
if not root:
return []
self.res.append(root.val)
for child in root.children:
self.preorder(child)
return self.res
897. 递增顺序查找树
class Solution:
def increasingBST(self, root: TreeNode) -> TreeNode:
self.x = ans = TreeNode(0)
def traverse(root):
if root:
traverse(root.left)
t = TreeNode(root.val)
self.x.right = t
self.x = t
traverse(root.right)
traverse(root)
return ans.right
112. 路径总和
class Solution:
def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:
if not root:
return False
if not root.left and not root.right:
return targetSum == root.val
return self.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(root.right, targetSum - root.val)
1022. 从根到叶的二进制数之和
class Solution:
def __init__(self):
self.res = 0
def sumRootToLeaf(self, root: TreeNode) -> int:
def traverse(root, s):
if not root:
return 0
s = s * 2 + root.val
if not root.left and not root.right:
self.res += s
traverse(root.left, s)
traverse(root.right, s)
traverse(root, 0)
return self.res
617. 合并二叉树
class Solution:
def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
if not t1:
return t2
if not t2:
return t1
if not t1 and not t2:
return None
root = TreeNode(t1.val + t2.val)
root.left = self.mergeTrees(t1.left, t2.left)
root.right = self.mergeTrees(t1.right, t2.right)
return root
107. 二叉树的层序遍历 II
class Solution:
def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
res = [[]]
def traverse(root, lev):
if not root:
return
res[lev-1].append(root.val)
if len(res) == lev:
res.append([])
traverse(root.left, lev+1)
traverse(root.right, lev+1)
traverse(root, 1)
return res[:-1][::-1]
100. 相同的树
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if q is None and p is not None:
return False
if p is None and q is not None:
return False
if p is None and q is None:
return True
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
404. 左叶子之和
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
if not root:
return 0
if root.left is None:
return self.sumOfLeftLeaves(root.right)
if root.left.left is None and root.left.right is None:
return root.left.val + self.sumOfLeftLeaves(root.right)
return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)
965. 单值二叉树
class Solution:
def isUnivalTree(self, root: TreeNode) -> bool:
left = not root.left or root.val == root.left.val and self.isUnivalTree(root.left)
right = not root.right or root.val == root.right.val and self.isUnivalTree(root.right)
return left and right
669. 修剪二叉搜索树
class Solution:
def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode:
def traverse(root, low ,high):
if not root:
return None
elif root.val < low:
return self.trimBST(root.right, low, high)
elif root.val > high:
return self.trimBST(root.left, low ,high)
else:
root.left = traverse(root.left, low ,high)
root.right = traverse(root.right, low, high)
return root
return traverse(root, low, high)
993. 二叉树的堂兄弟节点
class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
def traverse(root, parent, target, depth):
if not root:
return (-1, parent)
if root.val == target:
return (depth, parent)
l = traverse(root.left, root, target, depth + 1)
r = traverse(root.right, root, target, depth + 1)
if l[0] != -1:
return l
return r
dx, px = traverse(root, None, x, 0)
dy, py = traverse(root, None, y, 0)
if dx == dy and px != py:
return True
else:
return False
653. 两数之和 IV - 输入 BST
class Solution:
def findTarget(self, root: TreeNode, k: int) -> bool:
def traverse(root, k, tmp):
if not root:
return False
if k - root.val in tmp:
return True
tmp.add(root.val)
return traverse(root.left, k, tmp) or traverse(root.right, k, tmp)
tmp = set()
return traverse(root, k, tmp)
543. 二叉树的直径
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
if not root:
return 0
res = float("-inf")
def traverse(root):
nonlocal res
if not root:
return 0
left = traverse(root.left)
right = traverse(root.right)
res = max(left + right, res)
return max(left, right) + 1
traverse(root)
return res
树的子结构
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def HasSubtree(self, pRoot1, pRoot2):
result = False
if pRoot1 and pRoot2:
if pRoot1.val == pRoot2.val:
result = self.check_structure(pRoot1, pRoot2)
if not result:
result = self.HasSubtree(pRoot1.left, pRoot2)
if not result:
result = self.HasSubtree(pRoot1.right, pRoot2)
return result
def check_structure(self, root1, root2):
if not root2:
return True
if not root1:
return False
if root1.val != root2.val:
return False
left_check = self.check_structure(root1.left, root2.left)
right_check = self.check_structure(root1.right, root2.right)
return left_check and right_check