二叉树问题---二叉树节点间的最大距离

来源:互联网 发布:f1 2015知乎 编辑:程序博客网 时间:2024/06/05 06:43

问题:
  从二叉树节点A出发,可以向上或者向下走,但沿途的节点只能经过一次,当到达节点B时,路径上的节点数叫做A到B的距离。

基本思路:
一个以h为头的树上,最大的距离只可能来自以下三种情况:

  • h左子树上的最大距离
  • h右子树上的最大距离
  • h左子树上离h.left最远的距离+1+h右子树上离h.right最远的距离

三个值中的最大值就是整棵h树中最远的距离

#python3.5#二叉树节点间的最大距离def maxDistance(head):    def posOrder(head, record):        if head == None:            record[0] = 0            return 0        leftMax = posOrder(head.left, record)        maxfromLeft = record[0]        rightMax = posOrder(head.right, record)        maxfromRight = record[0]        record[0] = max(maxfromLeft, maxfromRight) + 1        curMax = maxfromLeft + maxfromRight + 1        return max(max(leftMax, rightMax),curMax)    if head == None:        return 0    record = [None]   #如果使用一个变量,则为值传递,record值不会变    return posOrder(head, record)