题解 | #二叉搜索树与双向链表#

二叉搜索树与双向链表

https://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5

/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
function Convert(pRootOfTree) {
    // write code here
    if(!pRootOfTree){
        return null
    }
    const nodeList = [];
    const traversal = (node) => {
        nodeList.push(node);
        if (node.left) {
            traversal(node.left);
        }
        if (node.right) {
            traversal(node.right);
        }
    };
    traversal(pRootOfTree);
    nodeList.sort((a, b) => a.val - b.val);
    for (let i = 0; i < nodeList.length - 1; i++) {
        nodeList[i].right = nodeList[i + 1];
        nodeList[i + 1].left = nodeList[i];
    }
    return nodeList[0];
}
module.exports = {
    Convert: Convert,
};

解题思路:用一个数组存放所有节点,然后再用每个节点的val进行排序,最后做左右指针的转化

#二叉搜索树与双向链表#
全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务