【python】二叉树求最大最小权值问题

题目链接:https://www.nowcoder.com/practice/d567727f21a247f7b64ba32431cb9a19

参考:https://blog.csdn.net/allisonton/article/details/52811135

思路:

分别找出根节点到该两点间的路径,再减去两者从根节点开始的共同路径距离

路径可用编码的形式来表示。

# -*- coding:utf-8 -*-

# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Tree:
    def __init__(self):
        self.min = 99999
        self.max = 0
        self.minpath = []
        self.maxpath = []
    def getDis(self, root):
        # write code here
        code = ''
        self.findpath(root,code,'0')
        a = self.minpath
        b = self.maxpath
        for i in range(min(len(a),len(b))):
            if a[i] != b[i]:
                return len(a[i:])+len(b[i:])
        return 0
    def findpath(self,root,code,flag):
        if not root:
            return
        code += flag
        if not root.left and not root.right:
            if self.max < root.val:
                self.max = root.val
                self.maxpath = code
            if self.min > root.val:
                self.min = root.val
                self.minpath = code
        self.findpath(root.left,code,'0')
        self.findpath(root.right,code,'1')

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值