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']> : [])
      ]
    : [];

在线演示

posted @ 2022-09-29 21:53  Laggage  阅读(29)  评论(0编辑  收藏  举报