Typescript类型体操 - InorderTraversal
题目
中文
实现二叉树的中序遍历
示例:
const tree1 = {
val: 1,
left: null,
right: {
val: 2,
left: {
val: 3,
left: null,
right: null,
},
right: null,
},
} as const;
type A = InorderTraversal<typeof tree1>; // [1, 3, 2]
English
Implement the type version of binary tree inorder traversal.
For example:
const tree1 = {
val: 1,
left: null,
right: {
val: 2,
left: {
val: 3,
left: null,
right: null,
},
right: null,
},
} as const;
type A = InorderTraversal<typeof tree1>; // [1, 3, 2]
答案
interface TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
}
type InorderTraversal<T extends TreeNode | null> = T extends TreeNode
? [
...(T['left'] extends TreeNode ? InorderTraversal<T['left']> : []),
T['val'],
...(T['right'] extends TreeNode ? InorderTraversal<T['right']> : [])
]
: [];