Binary Tree Nodes

  • + 1 comment

    Nearly identical in MySQL:

    select o.n, case when o.p is null then 'Root' when not exists(select * from bst where p=o.n) then 'Leaf' else 'Inner' end from bst o order by o.n

    According to the docs, using exists() is much more efficient because the db stops looking after the first match. In a large table, this could have a measureable impact. NOTE: you might think that in this particular example there would not be much benefit since each node has exactly one parent, and you'd be right, except that if the column is not indexed, there is no way for the db to know that, and it would still do a full table scan.