104.二叉树的最大深度
前序(中左右),后序遍历(左右中),使用前序求的就是深度,使用后序求的是高度。
- 二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数或者节点数(取决于深度从0开始还是从1开始)
- 二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数后者节点数(取决于高度从0开始还是从1开始)
559.n叉树的最大深度
class Solution:
def maxDepth(self, root: 'Node') -> int:
if not root:
return 0
depth = 0
que = [root]
while que:
depth += 1
for i in range(len(que)):
node = que.pop(0)
for j in range(len(node.children)):
if node.children[j]:
que.append(node.children[j])
return depth
111.二叉树的最小深度
空节点的高度是0
什么是叶子节点,左右孩子都为空的节点才是叶子节点
递归法
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
if not root.left and not root.right:
return 1
min_depth = 10**9
if root.left:
min_depth = min(self.minDepth(root.left), min_depth) # 获得左子树的最小高度
if root.right:
min_depth = min(self.minDepth(root.right), min_depth) # 获得右子树的最小高度
return min_depth + 1
222.完全二叉树的节点个数
利用满二叉树一定是完全二叉树,可以少遍历中间的节点,只要一直往左遍历的数量和一直往右遍历的数量是否相等,相等则是满二叉树,可以用2^n - 1来计算
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
return self.getNodesNum(root)
def getNodesNum(self,cur):
if not cur:
return 0
leftNum = self.getNodesNum(cur.left) #左
rightNum = self.getNodesNum(cur.right) #右
treeNum = leftNum + rightNum + 1 #中,遍历逻辑
return treeNum
迭代法
import collections
class Solution:
def countNodes(self, root: TreeNode) -> int:
queue = collections.deque()
if root:
queue.append(root)
result = 0
while queue:
size = len(queue)
for i in range(size):
node = queue.popleft()
result += 1 #记录节点数量
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return result
完全二叉树
class Solution:
def countNodes(self, root: TreeNode) -> int:
if not root:
return 0
left = root.left
right = root.right
leftDepth = 0 #这里初始为0是有目的的,为了下面求指数方便
rightDepth = 0
while left: #求左子树深度
left = left.left
leftDepth += 1
while right: #求右子树深度
right = right.right
rightDepth += 1
if leftDepth == rightDepth:
return (2 << leftDepth) - 1 #注意(2<<1) 相当于2^2,所以leftDepth初始为0
return self.countNodes(root.left) + self.countNodes(root.right) + 1
- 今日学习的文章链接
- 自己看到题目的第一想法
毫无头绪
- 看完代码随想录之后的想法
空节点的高度是0
- 自己实现过程中遇到哪些困难
- 今日收获,记录一下自己的学习时长