会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132358个问题
Python 全系列/第十六阶段:数据结构与算法/算法与数据结构(旧) 92楼

老师,我想求出二叉树中两个节点的距离,我的代码如下,函数已经写出来了,但是不知道如何返回level值,麻烦您帮我改一下,谢谢您了

class BiTNode:
    def __init__(self):
        self.data = None
        self.lchild = None
        self.rchild = None

def arraytotree(arr,start,end):
    #中序遍历生成二叉树
    root = None
    if end >= start:
        root = BiTNode()
        mid = (start+end+1)//2
        root.data = arr[mid]
        root.lchild = arraytotree(arr,start,mid-1)
        root.rchild = arraytotree(arr,mid+1,end)
    else:
        root = None
    return root

def FindParentNode(root,node1,node2):
    #找到公共父节点
    if root == None or root == node1 or root == node2:
        return root
    lchild = FindParentNode(root.lchild,node1,node2)
    rchild = FindParentNode(root.rchild,node1,node2)
    if lchild == None:
        return rchild
    elif rchild == None:
        return lchild
    else: return root

def printTree(root,node,level=1):
    #输出节点与根节点的距离level

    if root == node:
        return 0
    if root.lchild != None:
        if root.lchild == node:
            print(level)
        printTree(root.lchild,node,level=level+1)
    # print(root.data,end=" ")
    if root.rchild != None:
        if root.rchild == node:
            print(level)
        printTree(root.rchild,node,level=level+1)

if __name__=="__main__":
    arr = [1,2,3,4,5,6,7,8,9,10]
    root = arraytotree(arr,0,len(arr)-1)
    node1 = root.rchild.lchild.lchild
    node2 = root.lchild.rchild.lchild
    L = printTree(root,node1)
    M = printTree(root,node2)
    res = FindParentNode(root,node1,node2)
    N = printTree(root,res)
    print(L,M,N)
    distance = printTree(root,node1)+printTree(root,node2)-2*printTree(root,res)
    # if res != None:
    #     print(str(node1.data))
    #     print(str(node2.data))
    #     print(str(res.data))
    # print(distance)


Python 全系列/第十六阶段:数据结构与算法/算法与数据结构(旧) 94楼
Python 全系列/第十六阶段:数据结构与算法/数据结构与算法 96楼
Python 全系列/第十六阶段:数据结构与算法/算法与数据结构 97楼
Python 全系列/第十六阶段:数据结构与算法/算法与数据结构(旧) 99楼
Python 全系列/第十六阶段:数据结构与算法/算法与数据结构(旧) 102楼
Python 全系列/第十六阶段:数据结构与算法/数据结构与算法 103楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637