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

二叉搜索树与双向链表

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

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

相关推荐

07-15 12:24
重庆大学 运营
坏消息:和好工作擦肩而过
给点吧求求了:怎么可能因为差几秒,估计就是简历更好看婉拒了
点赞 评论 收藏
分享
头顶尖尖的程序员:我是26届的不太懂,25届不应该是找的正式工作吗?为什么还在找实习?大四还实习的话是为了能转正的的岗位吗
点赞 评论 收藏
分享
06-10 23:36
已编辑
首都经济贸易大学 C++
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务