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

二叉搜索树与双向链表

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进行排序,最后做左右指针的转化

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

相关推荐

28小凳也想实习:项目不用一个业务一个轮子吗,刷牛客好多人说要一业务一轮子
点赞 评论 收藏
分享
KPLACE:首先是板面看起来不够,有很多奖,比我厉害。项目要精减,大概详细描述两到三个,要把技术栈写清楚,分点,什么算法,什么外设,怎么优化,不要写一大堆,分点,你写上去的目的,一是让别人知道你做了这个知识点,然后在面试官技术面的时侯,他知道你会这个,那么就会跟你深挖这个,然后就是个人评价改为专业技能
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务