微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

二叉树中这个中序遍历的空间复杂度

如何解决二叉树中这个中序遍历的空间复杂度

下面是使用迭代的二叉树的顺序遍历函数。我希望空间复杂度保持不变。

输出一个包含 N 个元素的列表(N 将是二叉树中的节点数)。 但是由于列表的大小将取决于节点,所以这里的空间不能被认为是恒定的,对吗?

如果不是获取列表,而是在应该将节点附加到列表中时打印节点(如果列表存在),会使空间复杂度为 O(1) 吗?

我该怎么做才能使空间保持不变?

def inorder_traversal(tree,callback = []):

  prevIoUsNode = None
  currentNode = tree


  while currentNode is not None:

    #if it is the root node  or node with left child
    if prevIoUsNode is None or prevIoUsNode == currentNode.parent:
      if currentNode.left is not None:  #cant just add this we need to traverse the left subtree

        nextNode = currentNode.left
        
      else: #currentNode's left child is None so we can add the currentNode and then go to its right child if right child present or we go up

        callback.append(currentNode.value)

        nextNode = currentNode.right if currentNode.right is not None else currentNode.parent


    elif prevIoUsNode == currentNode.left:  #we have checked the left subtree of the left child so we add the left child

      callback.append(currentNode.value)

      nextNode = currentNode.right if currentNode.right is not None else currentNode.parent

    else:
      nextNode = currentNode.parent


    prevIoUsNode = currentNode
    currentNode = nextNode 


  return callback

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。