美文网首页
426. Convert Binary Search Tree

426. Convert Binary Search Tree

作者: jluemmmm | 来源:发表于2021-11-25 21:30 被阅读0次

    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;
    };
    

    相关文章

      网友评论

          本文标题:426. Convert Binary Search Tree

          本文链接:https://www.haomeiwen.com/subject/beeztrtx.html