返回
JavaScript实现LeetCode 897题:构建递增顺序搜索树
前端
2023-12-04 14:47:48
前言
LeetCode 897题要求将一个二叉搜索树(BST)转换为一个递增顺序的有序链表。本题解将使用递归的思想来实现。
首先,了解什么是二叉搜索树(BST)。BST是一种特殊的二叉树,它满足以下性质:
- 左子树中的所有节点的值都小于其父节点的值。
- 右子树中的所有节点的值都大于其父节点的值。
BST具有很重要的性质,即中序遍历BST可以得到一个递增有序的序列。因此,我们可以使用递归的中序遍历BST,并将访问到的节点的值存储到一个数组中。然后,我们将数组中的值按照从小到大的顺序排序,最后将这些值重新构造为一个递增顺序的有序链表。
代码实现
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* Given the root of a binary search tree, return a logically linked list of all the nodes' values in ascending order.
*
* @param {TreeNode} root The root node of the BST.
* @returns {ListNode} The head of the linked list.
*/
const increasingBST = (root) => {
// Initialize an empty array to store the values of the BST nodes.
const values = [];
// Perform an in-order traversal of the BST to collect the values.
const inorderTraversal = (node) => {
if (node === null) {
return;
}
// Recursively traverse the left subtree.
inorderTraversal(node.left);
// Add the current node's value to the array.
values.push(node.val);
// Recursively traverse the right subtree.
inorderTraversal(node.right);
};
// Perform the in-order traversal.
inorderTraversal(root);
// Sort the array of values in ascending order.
values.sort((a, b) => a - b);
// Create a new linked list to store the sorted values.
let head = new ListNode(values[0]);
let current = head;
// Iterate over the remaining values and add them to the linked list.
for (let i = 1; i < values.length; i++) {
const newNode = new ListNode(values[i]);
current.next = newNode;
current = newNode;
}
// Return the head of the linked list.
return head;
};
复杂度分析
- 时间复杂度:O(N),其中N是BST中的节点数。这是因为我们需要遍历BST中的每个节点一次,并且每个节点的处理时间为常数时间。
- 空间复杂度:O(N),这是因为我们需要创建一个数组来存储BST中的节点值。
总结
本题解使用递归的思想来实现将BST转换为一个递增顺序的有序链表。这种方法简单易懂,而且效率也很高。
希望本题解对您有所帮助!