426. Convert Binary Search Tree

2021-11-25  本文已影响0人  jluemmmm

BST转双向链表。输入一颗BST,将BST转换成一个排序的循环双向链表,要求不能创建任何新的节点,只能调整树中节点指针的指向。

对不起,这题我真理解不了

/**
 * // 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;
};
上一篇下一篇

猜你喜欢

热点阅读