已排序DLL到平衡BST的就地转换

给定一个双链表,其数据成员按升序排序。构建一个 平衡二叉搜索树 它的数据成员与给定的双链表相同。树必须就地构建(不应为树转换分配新节点)

null

例如:

Input:  Doubly Linked List 1  2  3Output: A Balanced BST      2      /      1    3 Input: Doubly Linked List 1  2 3  4 5  6  7Output: A Balanced BST        4      /        2     6   /     /   1   3  5   7  Input: Doubly Linked List 1  2  3  4Output: A Balanced BST      3       /       2    4  / 1Input:  Doubly Linked List 1  2  3  4  5  6Output: A Balanced BST      4       /        2     6  /     / 1   3  5   

双链表转换非常类似于 单链表问题 方法1与方法1完全相同 以前的职位 .方法2也几乎相同。方法2中唯一的区别是,我们重用相同的DLL节点,而不是为BST分配新节点。我们使用上一个指针作为左指针,下一个指针作为右指针。

方法1(简单) 下面是一个简单的算法,我们首先找到列表的中间节点,并使其成为要构造的树的根。

1) Get the Middle of the linked list and make it root.2) Recursively do same for left half and right half.       a) Get the middle of left half and make it left child of the root          created in step 1.       b) Get the middle of right half and make it right child of the          root created in step 1.

时间复杂度:O(nLogn),其中n是链表中的节点数。

方法2(棘手) 方法1从根到叶构建树。在这种方法中,我们从叶子到根进行构造。其思想是在BST中插入节点的顺序与它们在双链表中出现的顺序相同,这样就可以以O(n)时间复杂度构建树。我们首先计算给定链表中的节点数。设计数为n。在计算节点数之后,我们取左n/2个节点,递归地构造左子树。构造左子树后,我们将中间节点分配给根,并将左子树与根连接起来。最后,我们递归地构造正确的子树并将其与根连接起来。 在构造BST的同时,我们还将列表头指针移动到下一个,以便在每个递归调用中都有适当的指针。

下面是方法2的实现。创建平衡BST的主代码突出显示。

C++

#include <bits/stdc++.h>
using namespace std;
/* A Doubly Linked List node that
will also be used as a tree node */
class Node
{
public :
int data;
// For tree, next pointer can be
// used as right subtree pointer
Node* next;
// For tree, prev pointer can be
// used as left subtree pointer
Node* prev;
};
// A utility function to count nodes in a Linked List
int countNodes(Node *head);
Node* sortedListToBSTRecur(Node **head_ref, int n);
/* This function counts the number of
nodes in Linked List and then calls
sortedListToBSTRecur() to construct BST */
Node* sortedListToBST(Node *head)
{
/*Count the number of nodes in Linked List */
int n = countNodes(head);
/* Construct BST */
return sortedListToBSTRecur(&head, n);
}
/* The main function that constructs
balanced BST and returns root of it.
head_ref --> Pointer to pointer to
head node of Doubly linked list
n --> No. of nodes in the Doubly Linked List */
Node* sortedListToBSTRecur(Node **head_ref, int n)
{
/* Base Case */
if (n <= 0)
return NULL;
/* Recursively construct the left subtree */
Node *left = sortedListToBSTRecur(head_ref, n/2);
/* head_ref now refers to middle node,
make middle node as root of BST*/
Node *root = *head_ref;
// Set pointer to left subtree
root->prev = left;
/* Change head pointer of Linked List
for parent recursive calls */
*head_ref = (*head_ref)->next;
/* Recursively construct the right
subtree and link it with root
The number of nodes in right subtree
is total nodes - nodes in
left subtree - 1 (for root) */
root->next = sortedListToBSTRecur(head_ref, n-n/2-1);
return root;
}
/* UTILITY FUNCTIONS */
/* A utility function that returns
count of nodes in a given Linked List */
int countNodes(Node *head)
{
int count = 0;
Node *temp = head;
while (temp)
{
temp = temp->next;
count++;
}
return count;
}
/* Function to insert a node at
the beginning of the Doubly Linked List */
void push(Node** head_ref, int new_data)
{
/* allocate node */
Node* new_node = new Node();
/* put in the data */
new_node->data = new_data;
/* since we are adding at the beginning,
prev is always NULL */
new_node->prev = NULL;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* change prev of head node to new node */
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node ;
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Function to print nodes in a given linked list */
void printList(Node *node)
{
while (node!=NULL)
{
cout<<node->data<< " " ;
node = node->next;
}
}
/* A utility function to print
preorder traversal of BST */
void preOrder(Node* node)
{
if (node == NULL)
return ;
cout<<node->data<< " " ;
preOrder(node->prev);
preOrder(node->next);
}
/* Driver code*/
int main()
{
/* Start with the empty list */
Node* head = NULL;
/* Let us create a sorted linked list to test the functions
Created linked list will be 7->6->5->4->3->2->1 */
push(&head, 7);
push(&head, 6);
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
cout<< "Given Linked List" ;
printList(head);
/* Convert List to BST */
Node *root = sortedListToBST(head);
cout<< "PreOrder Traversal of constructed BST " ;
preOrder(root);
return 0;
}
// This code is contributed by rathbhupendra


C

#include<stdio.h>
#include<stdlib.h>
/* A Doubly Linked List node that will also be used as a tree node */
struct Node
{
int data;
// For tree, next pointer can be used as right subtree pointer
struct Node* next;
// For tree, prev pointer can be used as left subtree pointer
struct Node* prev;
};
// A utility function to count nodes in a Linked List
int countNodes( struct Node *head);
struct Node* sortedListToBSTRecur( struct Node **head_ref, int n);
/* This function counts the number of nodes in Linked List and then calls
sortedListToBSTRecur() to construct BST */
struct Node* sortedListToBST( struct Node *head)
{
/*Count the number of nodes in Linked List */
int n = countNodes(head);
/* Construct BST */
return sortedListToBSTRecur(&head, n);
}
/* The main function that constructs balanced BST and returns root of it.
head_ref -->  Pointer to pointer to head node of Doubly linked list
n  --> No. of nodes in the Doubly Linked List */
struct Node* sortedListToBSTRecur( struct Node **head_ref, int n)
{
/* Base Case */
if (n <= 0)
return NULL;
/* Recursively construct the left subtree */
struct Node *left = sortedListToBSTRecur(head_ref, n/2);
/* head_ref now refers to middle node, make middle node as root of BST*/
struct Node *root = *head_ref;
// Set pointer to left subtree
root->prev = left;
/* Change head pointer of Linked List for parent recursive calls */
*head_ref = (*head_ref)->next;
/* Recursively construct the right subtree and link it with root
The number of nodes in right subtree  is total nodes - nodes in
left subtree - 1 (for root) */
root->next = sortedListToBSTRecur(head_ref, n-n/2-1);
return root;
}
/* UTILITY FUNCTIONS */
/* A utility function that returns count of nodes in a given Linked List */
int countNodes( struct Node *head)
{
int count = 0;
struct Node *temp = head;
while (temp)
{
temp = temp->next;
count++;
}
return count;
}
/* Function to insert a node at the beginning of the Doubly Linked List */
void push( struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
( struct Node*) malloc ( sizeof ( struct Node));
/* put in the data  */
new_node->data  = new_data;
/* since we are adding at the beginning,
prev is always NULL */
new_node->prev = NULL;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* change prev of head node to new node */
if ((*head_ref) !=  NULL)
(*head_ref)->prev = new_node ;
/* move the head to point to the new node */
(*head_ref)    = new_node;
}
/* Function to print nodes in a given linked list */
void printList( struct Node *node)
{
while (node!=NULL)
{
printf ( "%d " , node->data);
node = node->next;
}
}
/* A utility function to print preorder traversal of BST */
void preOrder( struct Node* node)
{
if (node == NULL)
return ;
printf ( "%d " , node->data);
preOrder(node->prev);
preOrder(node->next);
}
/* Driver program to test above functions*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
/* Let us create a sorted linked list to test the functions
Created linked list will be 7->6->5->4->3->2->1 */
push(&head, 7);
push(&head, 6);
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
printf ( "Given Linked List" );
printList(head);
/* Convert List to BST */
struct Node *root = sortedListToBST(head);
printf ( " PreOrder Traversal of constructed BST " );
preOrder(root);
return 0;
}


JAVA

class Node
{
int data;
Node next, prev;
Node( int d)
{
data = d;
next = prev = null ;
}
}
class LinkedList
{
Node head;
/* This function counts the number of nodes in Linked List
and then calls sortedListToBSTRecur() to construct BST */
Node sortedListToBST()
{
/*Count the number of nodes in Linked List */
int n = countNodes(head);
/* Construct BST */
return sortedListToBSTRecur(n);
}
/* The main function that constructs balanced BST and
returns root of it.
n  --> No. of nodes in the Doubly Linked List */
Node sortedListToBSTRecur( int n)
{
/* Base Case */
if (n <= 0 )
return null ;
/* Recursively construct the left subtree */
Node left = sortedListToBSTRecur(n / 2 );
/* head_ref now refers to middle node,
make middle node as root of BST*/
Node root = head;
// Set pointer to left subtree
root.prev = left;
/* Change head pointer of Linked List for parent
recursive calls */
head = head.next;
/* Recursively construct the right subtree and link it
with root. The number of nodes in right subtree  is
total nodes - nodes in left subtree - 1 (for root) */
root.next = sortedListToBSTRecur(n - n / 2 - 1 );
return root;
}
/* UTILITY FUNCTIONS */
/* A utility function that returns count of nodes in a
given Linked List */
int countNodes(Node head)
{
int count = 0 ;
Node temp = head;
while (temp != null )
{
temp = temp.next;
count++;
}
return count;
}
/* Function to insert a node at the beginning of
the Doubly Linked List */
void push( int new_data)
{
/* allocate node */
Node new_node = new Node(new_data);
/* since we are adding at the beginning,
prev is always NULL */
new_node.prev = null ;
/* link the old list off the new node */
new_node.next = head;
/* change prev of head node to new node */
if (head != null )
head.prev = new_node;
/* move the head to point to the new node */
head = new_node;
}
/* Function to print nodes in a given linked list */
void printList()
{
Node node = head;
while (node != null )
{
System.out.print(node.data + " " );
node = node.next;
}
}
/* A utility function to print preorder traversal of BST */
void preOrder(Node node)
{
if (node == null )
return ;
System.out.print(node.data + " " );
preOrder(node.prev);
preOrder(node.next);
}
/* Driver program to test above functions */
public static void main(String[] args)
{
LinkedList llist = new LinkedList();
/* Let us create a sorted linked list to test the functions
Created linked list will be 7->6->5->4->3->2->1 */
llist.push( 7 );
llist.push( 6 );
llist.push( 5 );
llist.push( 4 );
llist.push( 3 );
llist.push( 2 );
llist.push( 1 );
System.out.println( "Given Linked List " );
llist.printList();
/* Convert List to BST */
Node root = llist.sortedListToBST();
System.out.println( "" );
System.out.println( "Pre-Order Traversal of constructed BST " );
llist.preOrder(root);
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)


C#

using System;
public class Node {
public int data;
public Node next, prev;
public Node( int d) {
data = d;
next = prev = null ;
}
}
public class List {
Node head;
/*
* This function counts the number of nodes in Linked List and then calls
* sortedListToBSTRecur() to construct BST
*/
Node sortedListToBST() {
/* Count the number of nodes in Linked List */
int n = countNodes(head);
/* Construct BST */
return sortedListToBSTRecur(n);
}
/*
* The main function that constructs balanced BST and returns root of it. n -->
* No. of nodes in the Doubly Linked List
*/
Node sortedListToBSTRecur( int n) {
/* Base Case */
if (n <= 0)
return null ;
/* Recursively construct the left subtree */
Node left = sortedListToBSTRecur(n / 2);
/*
* head_ref now refers to middle node, make middle node as root of BST
*/
Node root = head;
// Set pointer to left subtree
root.prev = left;
/*
* Change head pointer of Linked List for parent recursive calls
*/
head = head.next;
/*
* Recursively construct the right subtree and link it with root. The number of
* nodes in right subtree is total nodes - nodes in left subtree - 1 (for root)
*/
root.next = sortedListToBSTRecur(n - n / 2 - 1);
return root;
}
/* UTILITY FUNCTIONS */
/*
* A utility function that returns count of nodes in a given Linked List
*/
int countNodes(Node head) {
int count = 0;
Node temp = head;
while (temp != null ) {
temp = temp.next;
count++;
}
return count;
}
/*
* Function to insert a node at the beginning of the Doubly Linked List
*/
void Push( int new_data) {
/* allocate node */
Node new_node = new Node(new_data);
/*
* since we are adding at the beginning, prev is always NULL
*/
new_node.prev = null ;
/* link the old list off the new node */
new_node.next = head;
/* change prev of head node to new node */
if (head != null )
head.prev = new_node;
/* move the head to point to the new node */
head = new_node;
}
/* Function to print nodes in a given linked list */
void printList() {
Node node = head;
while (node != null ) {
Console.Write(node.data + " " );
node = node.next;
}
}
/* A utility function to print preorder traversal of BST */
void preOrder(Node node) {
if (node == null )
return ;
Console.Write(node.data + " " );
preOrder(node.prev);
preOrder(node.next);
}
/* Driver program to test above functions */
public static void Main(String[] args) {
List llist = new List();
/*
* Let us create a sorted linked list to test the functions Created linked list
* will be 7->6->5->4->3->2->1
*/
llist.Push(7);
llist.Push(6);
llist.Push(5);
llist.Push(4);
llist.Push(3);
llist.Push(2);
llist.Push(1);
Console.WriteLine( "Given Linked List " );
llist.printList();
/* Convert List to BST */
Node root = llist.sortedListToBST();
Console.WriteLine( "" );
Console.WriteLine( "Pre-Order Traversal of constructed BST " );
llist.preOrder(root);
}
}
// This code is contributed by Rajput-Ji


Javascript

<script>
class Node
{
constructor(d)
{
this .data=d;
this .next= this .prev= null ;
}
}
let head;
/* This function counts the number of nodes in Linked List
and then calls sortedListToBSTRecur() to construct BST */
function sortedListToBST()
{
/*Count the number of nodes in Linked List */
let n = countNodes(head);
/* Construct BST */
return sortedListToBSTRecur(n);
}
/* The main function that constructs balanced BST and
returns root of it.
n  --> No. of nodes in the Doubly Linked List */
function sortedListToBSTRecur(n)
{
/* Base Case */
if (n <= 0)
return null ;
/* Recursively construct the left subtree */
let left = sortedListToBSTRecur(Math.floor(n / 2));
/* head_ref now refers to middle node,
make middle node as root of BST*/
let root = head;
// Set pointer to left subtree
root.prev = left;
/* Change head pointer of Linked List for parent
recursive calls */
head = head.next;
/* Recursively construct the right subtree and link it
with root. The number of nodes in right subtree  is
total nodes - nodes in left subtree - 1 (for root) */
root.next = sortedListToBSTRecur(n - Math.floor(n / 2) - 1);
return root;
}
/* UTILITY FUNCTIONS */
/* A utility function that returns count of nodes in a
given Linked List */
function countNodes(head)
{
let count = 0;
let temp = head;
while (temp != null )
{
temp = temp.next;
count++;
}
return count;
}
/* Function to insert a node at the beginning of
the Doubly Linked List */
function push(new_data)
{
/* allocate node */
let new_node = new Node(new_data);
/* since we are adding at the beginning,
prev is always NULL */
new_node.prev = null ;
/* link the old list off the new node */
new_node.next = head;
/* change prev of head node to new node */
if (head != null )
head.prev = new_node;
/* move the head to point to the new node */
head = new_node;
}
/* Function to print nodes in a given linked list */
function printList()
{
let node = head;
while (node != null )
{
document.write(node.data + " " );
node = node.next;
}
}
/* A utility function to print preorder traversal of BST */
function preOrder(node)
{
if (node == null )
return ;
document.write(node.data + " " );
preOrder(node.prev);
preOrder(node.next);
}
/* Driver program to test above functions */
/* Let us create a sorted linked list to test the functions
Created linked list will be 7->6->5->4->3->2->1 */
push(7);
push(6);
push(5);
push(4);
push(3);
push(2);
push(1);
document.write( "Given Linked List <br>" );
printList();
/* Convert List to BST */
let root = sortedListToBST();
document.write( "<br>" );
document.write( "Pre-Order Traversal of constructed BST <br>" );
preOrder(root);
// This code is contributed by avanitrachhadiya2155
</script>


输出:

Given Linked List 1 2 3 4 5 6 7 Pre-Order Traversal of constructed BST 4 2 1 3 6 5 7 

时间复杂性: O(n)

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧,技术咨询可以联系QQ407933975
点赞15 分享