• 08-二叉树的下一个节点


    题目:给定一棵二叉树和其中其中的一个节点,如何找出中序遍历的下一个节点?树中的节点除了有两个分别指向左右子节点的指针,还有一个指向父节点的指针。

    def treeof2_next_node(head,node):
        hnode = head
        p = node
        if not hnode:
            return None
    
        if p.right:
            pright = p.right
            while pright.left:
                pright = pright.left
            return pright
        elif p.father.left == p:
            return p.father
    
        elif p.father.right == p:
            fnode = p.father
            if fnode.father == None:
                return None
            while fnode.father:
                if fnode.father.left == fnode:
                    return fnode.father
                fnode = fnode.father
            return None

    注:

    中序遍历下一个节点有三种情况

    1、如果该节点有右子树,下一个节点为右子树的最左节点

    2、如果该节点没有右子树,该节点为父节点的左子树,下一个节点为其父节点

    3、如果该节点没有右子树,该节点为父节点的右子树,向上找,一直到一个节点是其父节点的左子节点,下一个节点为该父节点;如果找不到,则没有下一个节点。

  • 相关阅读:
    2015IBM上海的一道笔试题
    通过SQL进行远程访问
    TreeSet集合
    Linux学习(11-23)
    使用OpenSessionInViewFilter的注意事项
    css position 几种定位
    css jquery 实现轮播效果
    jquery Jsonp的使用
    struts2的分页标签
    Elipse clean后无法编译出class文件
  • 原文地址:https://www.cnblogs.com/kingshine007/p/11342399.html
Copyright © 2020-2023  润新知