1.树
1.1 二叉树
1.1.1 二叉树的深度
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
ldepth = Solution.maxDepth(self, root.left)
rdepth = Solution.maxDepth(self, root.right)
return max(ldepth, rdepth) + 1
1.1.2 二叉搜索树的第k大节点
class Solution:
def kthLargest(self, root: TreeNode, k: int) -> int:
def func(root):
return func(root.left) +[root.val]+func(root.right) if root else []
return func(root)[-k]
1.1.3 二叉树的遍历
先序遍历
def pre_order(root):
if not root:
return []
return [root.val]+pre_order(root.left)+pre_order(root.right)
def pre_order(root):
if not root:
return
stack=[]
stack.append(root)
ret=[]
while stack:
x=stack.pop()
ret.append(x.val)
if x.right:
stack.append(x.right)
if x.left:
stack.append(x.left)
中序遍历
def mid_order(root):
if not root:
return []
return mid_order(root.left)+[root.val]+mid_order(root.right)
def mid_order(root):
if not root:
return
stack=[]
stack.append(root)
ret=[]
while stack:
x=stack.pop()
if x.right:
stack.append(x.right)
ret.append(x.val)
if x.left:
stack.append(x.left)
后序遍历
def post_order(root):
if not root:
return []
return post_order(root.left)+post_order(root.right)+[root.val]
def post_order(root):
if not root:
return
stack=[]
stack.append(root)
ret=[]
while stack:
x=stack.pop()
if x.right:
stack.append(x.right)
if x.left:
stack.append(x.left)
ret.append(x