DAY 16 | 104. Maximum Depth of Binary Tree | 111. Minimum Depth of Binary Tree | 222. Count Complet

该文描述了三个与二叉树相关的算法:计算最大深度、最小深度以及完全二叉树的节点数量。算法均采用后序遍历,对于最大深度,找到每个子树的最大深度并加1;对于最小深度,当遇到非空子树时更新最小深度;对于节点计数,判断是否为满二叉树并计算,否则递归计算左右子树节点数。

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)

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值