Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.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
Algorithm 遍历二叉树的最小成本是多少_Algorithm_Graph_Tree_Graph Algorithm_Tree Traversal - Fatal编程技术网

Algorithm 遍历二叉树的最小成本是多少

Algorithm 遍历二叉树的最小成本是多少,algorithm,graph,tree,graph-algorithm,tree-traversal,Algorithm,Graph,Tree,Graph Algorithm,Tree Traversal,我想以最小代价遍历一棵二叉树,其中每条边的代价是1。 当访问树的每个节点时,遍历完成。 例如,遍历以下树的最小代价是13 * / \ * * / \ \ * * * / / \ * * * 遍历以下树的最小代价是12 * / \ * * / \ \ * * * / \ * * / * 遍

我想以最小代价遍历一棵二叉树,其中每条边的代价是1。 当访问树的每个节点时,遍历完成。

例如,遍历以下树的最小代价是13

       *
      / \
     *   *
    / \   \
   *   *   *
  /   /     \
 *   *       *
遍历以下树的最小代价是12

        *
       / \
      *   *
     / \   \
    *   *   *
   /     \
  *       *
 /
*

遍历树的代价是
n-1
,其中
n
是节点数

这是正确的,因为每棵树都有确切的
n-1
边-您需要使用所有这些边才能访问所有节点


确切地说,下面3条语句对于具有
n
节点的图
T
是等效的:

  • T是一棵树(无圈连接)
  • T是连通的,有n-1条边
  • T没有循环,有n-1条边
  • 从上面我们可以得出结论,在一棵树中,为了到达所有节点,我们必须使用所有的边(因为没有循环,所以没有多余的边),而这些边中正好有
    n-1


    编辑

    从您的示例来看,您似乎也在计算从每条边返回的次数(即,某些边被计算两次)

    在这种情况下,最佳解决方案是:

    cost = (n-1)*2 - height
    
    解释/证明指南:
    树中正好有
    n-1
    边。除从根节点到最深节点的节点外,每个节点都被精确地遍历两次。
    您必须精确地使用每个边(除了提到的边)两次,因为除了最后一个分支之外,您可以从每个节点返回。
    因为在最后一个分支中正好有
    height
    边,所以您得到了
    cost=(n-1)*2-height

    请注意,它与您得到的基本相同:

    height + 2*(n-1-height) = height + 2(n-1) -2height = 2(n-1) - height