Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 二叉树中这种有序遍历的空间复杂度_Python_Binary Tree_Tree Traversal_Space Complexity - Fatal编程技术网

Python 二叉树中这种有序遍历的空间复杂度

Python 二叉树中这种有序遍历的空间复杂度,python,binary-tree,tree-traversal,space-complexity,Python,Binary Tree,Tree Traversal,Space Complexity,下面是使用迭代对二叉树进行顺序遍历的函数。我希望空间的复杂性是恒定的 输出是一个包含N个元素的列表(N是二叉树中的节点数)。 但是由于列表的大小取决于节点,所以这里的空间不能被认为是恒定的,对吗 如果不是获取列表,而是在应该将节点追加到列表中时打印节点(如果列表存在),这会使空间复杂度为O(1) 我该怎么做才能使这个空间保持不变 def inorder_traversal(tree,callback = []): previousNode = None currentNode = tr

下面是使用迭代对二叉树进行顺序遍历的函数。我希望空间的复杂性是恒定的

输出是一个包含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


看起来像O(n)空间复杂性。变量
callback
根据树的大小增长。递归解决方案可以保持空间复杂度不变:@pavel我们必须使用迭代。