Total number of nodes in a tree data structure?

后端 未结 6 559
无人共我
无人共我 2021-01-31 05:38

I have a tree data structure that is L levels deep each node has about N nodes. I want to work-out the total number of nodes in the tree. To do this (I think) I

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-31 06:29

    Knuth's estimator [1],[2] is a point estimate that targets the number of nodes in an arbitrary finite tree without needing to go through all of the nodes and even if the tree is not balanced. Knuth's estimator is an example of an unbiased estimator; the expected value of Knuth's estimator will be the number of nodes in the tree. With that being said, Knuth's estimator may have a large variance if the tree in question is unbalanced, but in your case, since each node will have around N children, I do not think the variance of Knuth's estimator should be too large. This estimator is especially helpful when one is trying to measure the amount of time it will take to perform a brute force search.

    For the following functions, we shall assume all trees are represented as lists of lists. For example, [] denotes the tree with the single node, and [[],[[],[]]] will denote a tree with 5 nodes and 3 leaves (the nodes in the tree are in a one-to-one correspondence with the left brackets). The following functions are written in the language GAP.

    The function simpleestimate gives an output an estimate for the number of nodes in the tree tree. The idea behind simpleestimate is that we randomly choose a path x_0,x_1,...,x_n from the root x_0 of the tree to a leaf x_n. Suppose that x_i has a_i successors. Then simpleestimate will return 1+a_1+a_1*a_2+...+a_1*a_2*…*a_n.

    point:=tree; prod:=1; count:=1; list:=[]; 
    while Length(point)>0 do prod:=prod*Length(point); count:=count+prod; point:=Random(point); od;
    return count; end;
    

    The function estimate will simply give the arithmetical mean of the estimates given by applying the function simpleestimate(tree) samplesize many times.

    estimate:=function(samplesize,tree) local count,i; 
    count:=0; 
    for i in [1..samplesize] do count:=count+simpleestimate(tree); od; 
    return Float(count/samplesize); end;
    

    Example: simpleestimate([[[],[[],[]]],[[[],[]],[]]]); returns 15 while estimate(10000,[[[],[[],[]]],[[[],[]],[]]]); returns 10.9608 (and the tree actually does have 11 nodes).

    1. Estimating Search Tree Size. http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.129.5569&rep=rep1&type=pdf

    2. Estimating the Efficiency of Backtrack Programs. Donald E. Knuth http://www.ams.org/journals/mcom/1975-29-129/S0025-5718-1975-0373371-6/S0025-5718-1975-0373371-6.pdf

提交回复
热议问题