终止条件:root == None
max(左,右子树最大深度) + 1
- class Solution:
- def maxDepth(self, root: Optional[TreeNode]) -> int:
- if not root:
- return 0
- leftDepth = self.maxDepth(root.left)
- rightDepth = self.maxDepth(root.right)
- Depth = 1 + max(leftDepth, rightDepth)
- return Depth
如果左右子树都存在 那么 minDepth = min(左,右子树最小深度)+ 1
如果只存在左/右子树 那么 minDepth = min(左 / 右子树最小深度)+ 1
如果左右子树 都不存在 minDepth = 1
- class Solution:
- def minDepth(self, root: Optional[TreeNode]) -> int:
- if not root:
- return 0
- if root.right and root.left:
- leftDepth = self.minDepth(root.left)
- rightDepth = self.minDepth(root.right)
- Depth = 1 + min(leftDepth, rightDepth)
- elif root.right and not root.left:
- Depth = 1 + self.minDepth(root.right)
- elif not root.right and root.left:
- Depth = 1 + self.minDepth(root.left)
- else:
- Depth = 1
- return Depth
- class Solution:
- def countNodes(self, root: Optional[TreeNode]) -> int:
- if not root:
- return 0
- rightN = self.countNodes(root.right)
- leftN = self.countNodes(root.left)
- return rightN + leftN + 1
递归的思想 节点数 = 左子树节点数 + 右子树节点数 + 1