426. Convert Binary Search Tree to Sorted Doubly Linked List

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;
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容