Skip to content

Commit 96f43df

Browse files
committed
feat: post-order traversal
Signed-off-by: Andres Correa Casablanca <castarco@coderspirit.xyz>
1 parent 5d01636 commit 96f43df

File tree

6 files changed

+67
-3
lines changed

6 files changed

+67
-3
lines changed

.github/workflows/tests.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,4 +41,4 @@ jobs:
4141
- name: Build Library
4242
run: pnpm build
4343
- name: Run Tests
44-
run: pnpm test
44+
run: pnpm test:coverage

src/BeautifulTree.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { Tree } from './core'
1+
import type { Tree } from './layouts'
22

33
export interface BeautifulTreeProps {
44
readonly id: string
File renamed without changes.

src/tests/core.test.ts renamed to src/tests/layouts.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { describe, expect, it } from 'vitest'
2-
import { computeLeftShiftLayout } from '../core'
2+
import { computeLeftShiftLayout } from '../layouts'
33

44
describe('computeLeftShiftLayout', () => {
55
it('sets x=0,y=0 for a single-node tree, and data is preserved', () => {

src/tests/traversal.test.ts

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import { describe, expect, it } from 'vitest'
2+
import { postOrderIterator } from '../traversal'
3+
4+
describe('postOrderIterator', () => {
5+
const testTree = {
6+
data: { v: 42 },
7+
children: [
8+
{
9+
edgeData: {},
10+
node: {
11+
data: { v: 43 },
12+
children: [
13+
{
14+
edgeData: {},
15+
node: { data: { v: 45 } },
16+
},
17+
],
18+
},
19+
},
20+
{
21+
edgeData: {},
22+
node: {
23+
data: { v: 44 },
24+
children: [
25+
{
26+
edgeData: {},
27+
node: { data: { v: 46 } },
28+
},
29+
{
30+
edgeData: {},
31+
node: { data: { v: 47 } },
32+
},
33+
],
34+
},
35+
},
36+
],
37+
}
38+
39+
it('traverses tree in post-order', () => {
40+
const result = postOrderIterator(testTree)
41+
42+
console.log('result:')
43+
const expandedResult = [...result]
44+
45+
expect(expandedResult).toEqual([
46+
{ v: 45 },
47+
{ v: 43 },
48+
{ v: 46 },
49+
{ v: 47 },
50+
{ v: 44 },
51+
{ v: 42 },
52+
])
53+
})
54+
})

src/traversal.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import type { Tree, TreeWithLayout } from './layouts'
2+
3+
export function* postOrderIterator<T extends Tree | TreeWithLayout = Tree>(
4+
v: Readonly<T>,
5+
): Generator<T['data'], void> {
6+
for (const child of v.children ?? []) {
7+
yield* postOrderIterator<T>(child.node as T)
8+
}
9+
yield v.data
10+
}

0 commit comments

Comments
 (0)