【求二叉树的最长路径】

  • 自定义二叉树,并求出二叉树的最长路径
  • 思路:求出二叉树的深度depth,再遍历一遍二叉树,找到并记录长度为depth的路径即可。
#
# time:2022年4月23日23:12:21
# author:Wupke
# description: 求二叉树的最长路径,思路:求出二叉树的深度depth,再遍历一遍二叉树,找到并记录长度为depth的路径即可。

class TreeNode:  # 定义二叉树
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:

    def Depth(self,node):   # 求二叉树的深度
        if not node :return 0
        left = self.Depth(node.left)
        right = self.Depth(node.right)
        return max(left,right)+1

    def Preorder(self,node,path): # 遍历二叉树,并记录符合的路径节点
        if not node:return

        path.append(node.val)
        
        if not node.left and not node.right and len(path) == depth:
            path_res.append(path[:])

        self.Preorder(node.left, path)
        self.Preorder(node.right, path)
        path.pop()  # 回溯
        return path_res

if __name__=="__main__":
    s = Solution()
    root = TreeNode(5)
    root.left = TreeNode(4)        
    root.right = TreeNode(8)
    root.left.left = TreeNode(11)
    root.left.left.left = TreeNode(7)
    root.left.left.right = TreeNode(2)
    # 运行结果:  res:  [[5, 4, 11, 7], [5, 4, 11, 2]]

    # root = TreeNode(5)
    # root.left = TreeNode(4)
    # root.left.left = TreeNode(3)
    # root.left.right = TreeNode(7)
    # root.left.right.left = TreeNode(6)
    # root.left.right.right = TreeNode(8)
    # root.left.right.left.right = TreeNode(2)
    # root.left.right.right.right = TreeNode(1)
    # root.left.right.right.right.left = TreeNode(9)
    # ## 运行结果: res:  [[5, 4, 7, 8, 1, 9]]

    path = list()
    path_res = list()
    depth = s.Depth(root)
    print("root depth :", depth)
    # result = s.longerestPath(root)
    result = s.Preorder(root,path)
    print("res: ",result)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值