104. Maximum Depth of Binary Tree
1. parameters: node
2. terminal: when the input of the node is None (end of the tree)
3. logic of a single layer: post-order. every level find max depth of the sub-tree and + 1
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
def get_max(node):
if not node:
return 0
left = get_max(node.left)
right = get_max(node.right)
depth = max(left,right) + 1
return depth
return get_max(root)
111. Minimum Depth of Binary Tree
1. parameters: node
2. terminal: when the input of the node is None (end of the tree)
3. logic of a single layer: post-order. every level find min depth of the sub-tree and + 1. When comparing the two sub nodes, exclude the one if equals to None. because we're calculating the depth to the end leaf.
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
def get_min(node):
if not node:
return 0
left = get_min(node.left)
right = get_min(node.right)
if left != 0 and right == 0:
return left + 1
elif left == 0 and right != 0:
return right + 1
else:
return min(left, right) + 1
return get_min(root)
222. Count Complete Tree Nodes
1. parameters: node
2. terminal condition: 1. when the input of the node is None (end of the tree) 2. when the length of outer left and outer right is equal (full binary tree)
3. logic of a single layer: post-order. From an input node, find if it's a full binary tree. if so, calculate the number of nodes, if not, move to the left and right child node.
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
left_count = 0
right_count = 0
left = root.left
right = root.right
while(left):
left = left.left
left_count += 1
while(right):
right = right.right
right_count += 1
if left_count == right_count:
return (2 << left_count) - 1
return(self.countNodes(root.left) + self.countNodes(root.right) + 1)
该文描述了三个与二叉树相关的算法:计算最大深度、最小深度以及完全二叉树的节点数量。算法均采用后序遍历,对于最大深度,找到每个子树的最大深度并加1;对于最小深度,当遇到非空子树时更新最小深度;对于节点计数,判断是否为满二叉树并计算,否则递归计算左右子树节点数。

被折叠的 条评论
为什么被折叠?



