Tree traversal using a cursor and .firstChild() skipping a leaf

Hi, I’m trying to traverse the tree and push the leaves to a list. To do this, I’m using the below logic, which works when there is only one node at Level 1/(single query). But when it comes to to two queries or two nodes at Level 1, the first leaf of the second query gets skipped.

do {
    if (!cursor.firstChild()) {
    list.push(cursor.name);
  }
} while (cursor.next());

Here is the parse tree for it.

Lang [0..41]
 ├─ Expression [1..19]
 │   └─ Statement [1..19]
 │       └─ SelectStmt [1..19]
 │           ├─ Select [1..7]: "select"
 │           ├─ * [8..9]: "*"
 │           ├─ From [10..14]: "from"
 │           ├─ Identifier [15..18]: "val_a"
 │           └─ ; [18..19]: ";"
 └─ Expression [20..40]
     └─ Statement [20..40]
         └─ SelectStmt [20..40]
             ├─ Select [20..26]: "select"
             ├─ * [27..28]: "*"
             ├─ From [29..33]: "from"
             ├─ Identifier [34..39]: "val_b"
             └─ ; [39..40]: ";"

Any help would be appreciated!

cursor.firstChild will move the cursor, so if you then call cursor.next you’ll end up skipping nodes. Something like this might work (untested):

for (;;) {
  if (!cursor.firstChild()) {
    list.push(cursor.name)
    if (!cursor.next()) break
  }
}
1 Like

Many thanks, that worked.