题目链接: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')