Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Well, if there's duplicates, then the depth of a node with a given value doesn't make any sense on its own, because there may be multiple nodes with that value, hence multiple depths.</p> <p><em>You</em> have to decide what it means, which could be (not necessarily an exhaustive list):</p> <ul> <li>the depth of the deepest node with that value.</li> <li>the depth of the shallowest node with that value.</li> <li>the depth of the first node found with that value.</li> <li>the average depth of all nodes with that value.</li> <li>the range (min/max) of depths of all nodes with that value.</li> <li>a list of depths of all nodes with that value.</li> <li>an error code indicating your query made little sense.</li> </ul> <p><em>Any</em> of those could make sense in specific circumstances.</p> <hr> <p>Of course, if <code>n</code> is an actual pointer to a node, you shouldn't be comparing <em>values of nodes</em> at all, you should be comparing pointers. That way, you will only ever find <em>one</em> match and the depth of it makes sense.</p> <p>Something like the following pseudo-code should do:</p> <pre><code>def getDepth (Node needle, Node haystack, int value): // Gone beyond leaf, it's not in tree if haystack == NULL: return -1 // Pointers equal, you've found it. if needle == haystack: return value // Data not equal search either left or right subtree. if needle.data &lt; haystack.data: return getDepth (needle, haystack.left, value + 1) if needle.data &gt; haystack.data: return getDepth (needle, haystack.right, value + 1) // Data equal, need to search BOTH subtrees. tryDepth = getDepth (needle, haystack.left, value + 1) if trydepth == -1: tryDepth = getDepth (needle, haystack.right, value + 1) return trydepth </code></pre> <p>The reason why you have to search <em>both</em> subtrees when the values are equal is because the desired node may be in either subtree. Where the values are unequal, you know which subtree it's in. So, for the case where they're equal, you check one subtree and, if not found, you check the other.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload