二叉树包含节点:一个节点包含节点值及子节点
class TreeNode: def __init__(self,val =0, left = None, right = None): self.val = val self.left = left self.right = right # 给二叉树的根节点,返回节点值的前序遍历 class Solution: # 前序遍历(根-左-右) def preorderTraversal(self, root: TreeNode) -> list: list = [] def per(root): if not root: return list.append(root.val) per(root.left) per(root.right) per(root) return list # 中序遍历(左-根-右) def preorder(self, root: TreeNode) -> list: list = [] def per(root): if not root: return per(root.left) list.append(root.val) per(root.right) per(root) return list # 后序遍历(左-根-右) def preorder_right(self, root: TreeNode) -> list: list = [] def per(root): if not root: return per(root.left) per(root.right) list.append(root.val) per(root) return list # 求二叉树的深度 def maxDepth(self, root: TreeNode): if root is None: # 递归的终止条件:最后一个节点的子节点深度为0 return 0 else: # left_height = self.maxDepth(root.left) # right_height = self.maxDepth(root.right) # return max(left_height, right_height) + 1 return max(self.maxDepth(root.left),self.maxDepth(root.right))+1 # 每一个节点的深度都等于他的子节点+1 s = Solution() r1 = TreeNode(1) r2 = TreeNode(2) r3 = TreeNode(3) r4 = TreeNode(4) r1.left = r2 r1.right = r4 r2.left = r3 # s.preorderTraversal(r1) print(s.maxDepth(r1))