算法练习Day14 (Leetcode/Python-二叉树)

104. Maximum Depth of Binary Tree

Given the root of a binary tree, return its maximum depth.

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

思路:其实就是左右中的后序遍历。具体见昨天的练习。

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def maxDepth(self, root):
        return self.getdepth(root)
        
    def getdepth(self, node):
        if not node:
            return 0
        leftheight = self.maxDepth(node.left)
        rightheight = self.maxDepth(node.right) 
        height = 1 + max(leftheight, rightheight)
        return height

222. Count Complete Tree Nodes

类似上一题,但是这题是计算node个树。

class Solution:
    def countNodes(self, root: TreeNode) -> int:
        return self.getNodesNum(root)
        
    def getNodesNum(self, cur):
        if not cur:
            return 0
        leftNum = self.getNodesNum(cur.left) #left
        rightNum = self.getNodesNum(cur.right) #right
        treeNum = leftNum + rightNum + 1 #middle
        return treeNum

111. Minimum Depth of Binary Tree


 

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Note: A leaf is a node with no children.

只有当一个节点的左右节点都为空时,才是最低点。画出一个这样的二叉树就知道了。

class Solution:
    def getDepth(self, node):
        if node is None:
            return 0
        leftDepth = self.getDepth(node.left)  
        rightDepth = self.getDepth(node.right) 
        
        # only when both left and right are empty, it is the lowest point
        if node.left is None and node.right is not None:
            return 1 + rightDepth
        if node.left is not None and node.right is None:
            return 1 + leftDepth
        
        result = 1 + min(leftDepth, rightDepth)
        return result

    def minDepth(self, root):
        return self.getDepth(root)  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值