426. Convert Binary Search Tree
2021-11-25 本文已影响0人
jluemmmm
BST转双向链表。输入一颗BST,将BST转换成一个排序的循环双向链表,要求不能创建任何新的节点,只能调整树中节点指针的指向。
对不起,这题我真理解不了
- 时间复杂度O(n),空间复杂度O(n)
- Runtime: 111 ms, faster than 12.70%
- Memory Usage: 40.6 MB, less than 15.87%
/**
* // Definition for a Node.
* function Node(val, left, right) {
* this.val = val;
* this.left = left;
* this.right = right;
* };
*/
/**
* @param {Node} root
* @return {Node}
*/
var treeToDoublyList = function(root) {
if (!root) return null;
let first = null;
let last = null;
const recursive = function(node) {
if (node) {
recursive(node.left);
if (last) {
last.right = node;
node.left = last;
} else {
first = node;
}
last = node;
recursive(node.right);
}
}
recursive(root);
last.right = first;
first.left = last;
return first;
};