BST가 주어지면 ( 비 단원 에스 귀 티 ree) 불균형할 수 있는 경우 가능한 최소 높이를 갖는 균형 잡힌 BST로 변환합니다.
예:
Input: 30 / 20 / 10 Output: 20 / 10 30 Input: 4 / 3 / 2 / 1 Output: 3 3 2 / / / 1 4 OR 2 4 OR 1 3 OR .. / 2 1 4 Input: 4 / 3 5 / 2 6 / 1 7 Output: 4 / 2 6 / / 1 3 5 7>추천 연습 일반 BST부터 균형 잡힌 BST까지 시도해 보세요!
ㅏ 간단한 솔루션 순서대로 노드를 순회하고 AVL 트리와 같은 자체 균형 BST에 하나씩 삽입하는 것입니다. 이 솔루션의 시간 복잡도는 O(n Log n)이며 최악의 경우 AVL 트리의 높이가 다음과 같을 수 있으므로 이 솔루션은 가능한 최소 높이를 보장하지 않습니다. 1.44*로그 2 N .
안 효율적인 솔루션 가능한 최소 높이로 O(n) 시간에 균형 잡힌 BST를 구성하는 것이 가능합니다. 다음은 단계입니다.
- 주어진 BST를 중순으로 순회하고 결과를 배열에 저장합니다. 이 단계에는 O(n) 시간이 걸립니다. 이 배열은 BST의 중위 순회가 항상 정렬된 시퀀스를 생성하므로 정렬됩니다.
- 논의된 재귀 접근 방식을 사용하여 위에서 생성된 정렬된 배열에서 균형 잡힌 BST를 구축합니다. 여기 . 모든 요소를 정확히 한 번만 탐색하고 요소를 처리하는 데 O(1) 시간이 걸리기 때문에 이 단계에도 O(n) 시간이 걸립니다.
다음은 위 단계의 구현입니다.
C++
// C++ program to convert a left unbalanced BST to> // a balanced BST> #include> using> namespace> std;> struct> Node> {> >int> data;> >Node* left, *right;> };> /* This function traverse the skewed binary tree and> >stores its nodes pointers in vector nodes[] */> void> storeBSTNodes(Node* root, vector &nodes)> {> >// Base case> >if> (root==NULL)> >return>;> >// Store nodes in Inorder (which is sorted> >// order for BST)> >storeBSTNodes(root->왼쪽, 노드);> >nodes.push_back(root);> >storeBSTNodes(root->오른쪽, 노드);> }> /* Recursive function to construct binary tree */> Node* buildTreeUtil(vector &nodes,>int> start,> >int> end)> {> >// base case> >if> (start>끝)> >return> NULL;> >/* Get the middle element and make it root */> >int> mid = (start + end)/2;> >Node *root = nodes[mid];> >/* Using index in Inorder traversal, construct> >left and right subtress */> >root->왼쪽 = buildTreeUtil(노드, 시작, mid-1);> >root->right = buildTreeUtil(노드, mid+1, end);> >return> root;> }> // This functions converts an unbalanced BST to> // a balanced BST> Node* buildTree(Node* root)> {> >// Store nodes of given BST in sorted order> >vector nodes;> >storeBSTNodes(root, nodes);> >// Constructs BST from nodes[]> >int> n = nodes.size();> >return> buildTreeUtil(nodes, 0, n-1);> }> // Utility function to create a new node> Node* newNode(>int> data)> {> >Node* node =>new> Node;> >node->데이터 = 데이터;> >node->왼쪽 = 노드->오른쪽 = NULL;> >return> (node);> }> /* Function to do preorder traversal of tree */> void> preOrder(Node* node)> {> >if> (node == NULL)> >return>;> >printf>(>'%d '>, node->데이터);> >preOrder(node->왼쪽);> >preOrder(node->오른쪽);> }> // Driver program> int> main()> {> >/* Constructed skewed binary tree is> >10> >/> >8> >/> >7> >/> >6> >/> >5 */> >Node* root = newNode(10);> >root->왼쪽 = newNode(8);> >root->왼쪽->왼쪽 = newNode(7);> >root->왼쪽->왼쪽->왼쪽 = newNode(6);> >root->왼쪽->왼쪽->왼쪽->왼쪽 = newNode(5);> >root = buildTree(root);> >printf>(>'Preorder traversal of balanced '> >'BST is :
'>);> >preOrder(root);> >return> 0;> }> |
>
자식 푸시 명령
>
자바
자바의 인터페이스
// Java program to convert a left unbalanced BST to a balanced BST> import> java.util.*;> /* A binary tree node has data, pointer to left child> >and a pointer to right child */> class> Node> {> >int> data;> >Node left, right;> >public> Node(>int> data)> >{> >this>.data = data;> >left = right =>null>;> >}> }> class> BinaryTree> {> >Node root;> >/* This function traverse the skewed binary tree and> >stores its nodes pointers in vector nodes[] */> >void> storeBSTNodes(Node root, Vector nodes)> >{> >// Base case> >if> (root ==>null>)> >return>;> >// Store nodes in Inorder (which is sorted> >// order for BST)> >storeBSTNodes(root.left, nodes);> >nodes.add(root);> >storeBSTNodes(root.right, nodes);> >}> >/* Recursive function to construct binary tree */> >Node buildTreeUtil(Vector nodes,>int> start,> >int> end)> >{> >// base case> >if> (start>끝)> >return> null>;> >/* Get the middle element and make it root */> >int> mid = (start + end) />2>;> >Node node = nodes.get(mid);> >/* Using index in Inorder traversal, construct> >left and right subtress */> >node.left = buildTreeUtil(nodes, start, mid ->1>);> >node.right = buildTreeUtil(nodes, mid +>1>, end);> >return> node;> >}> >// This functions converts an unbalanced BST to> >// a balanced BST> >Node buildTree(Node root)> >{> >// Store nodes of given BST in sorted order> >Vector nodes =>new> Vector();> >storeBSTNodes(root, nodes);> >// Constructs BST from nodes[]> >int> n = nodes.size();> >return> buildTreeUtil(nodes,>0>, n ->1>);> >}> >/* Function to do preorder traversal of tree */> >void> preOrder(Node node)> >{> >if> (node ==>null>)> >return>;> >System.out.print(node.data +>' '>);> >preOrder(node.left);> >preOrder(node.right);> >}> >// Driver program to test the above functions> >public> static> void> main(String[] args)> >{> >/* Constructed skewed binary tree is> >10> >/> >8> >/> >7> >/> >6> >/> >5 */> >BinaryTree tree =>new> BinaryTree();> >tree.root =>new> Node(>10>);> >tree.root.left =>new> Node(>8>);> >tree.root.left.left =>new> Node(>7>);> >tree.root.left.left.left =>new> Node(>6>);> >tree.root.left.left.left.left =>new> Node(>5>);> >tree.root = tree.buildTree(tree.root);> >System.out.println(>'Preorder traversal of balanced BST is :'>);> >tree.preOrder(tree.root);> >}> }> // This code has been contributed by Mayank Jaiswal(mayank_24)> |
>
>
파이썬3
# Python3 program to convert a left> # unbalanced BST to a balanced BST> import> sys> import> math> # A binary tree node has data, pointer to left child> # and a pointer to right child> class> Node:> >def> __init__(>self>,data):> >self>.data>=>data> >self>.left>=>None> >self>.right>=>None> # This function traverse the skewed binary tree and> # stores its nodes pointers in vector nodes[]> def> storeBSTNodes(root,nodes):> > ># Base case> >if> not> root:> >return> > ># Store nodes in Inorder (which is sorted> ># order for BST)> >storeBSTNodes(root.left,nodes)> >nodes.append(root)> >storeBSTNodes(root.right,nodes)> # Recursive function to construct binary tree> def> buildTreeUtil(nodes,start,end):> > ># base case> >if> start>끝:> >return> None> ># Get the middle element and make it root> >mid>=>(start>+>end)>/>/>2> >node>=>nodes[mid]> ># Using index in Inorder traversal, construct> ># left and right subtress> >node.left>=>buildTreeUtil(nodes,start,mid>->1>)> >node.right>=>buildTreeUtil(nodes,mid>+>1>,end)> >return> node> # This functions converts an unbalanced BST to> # a balanced BST> def> buildTree(root):> > ># Store nodes of given BST in sorted order> >nodes>=>[]> >storeBSTNodes(root,nodes)> ># Constructs BST from nodes[]> >n>=>len>(nodes)> >return> buildTreeUtil(nodes,>0>,n>->1>)> # Function to do preorder traversal of tree> def> preOrder(root):> >if> not> root:> >return> >print>(>'{} '>.>format>(root.data),end>=>'')> >preOrder(root.left)> >preOrder(root.right)> # Driver code> if> __name__>=>=>'__main__'>:> ># Constructed skewed binary tree is> ># 10> ># /> ># 8> ># /> ># 7> ># /> ># 6> ># /> ># 5> >root>=> Node(>10>)> >root.left>=> Node(>8>)> >root.left.left>=> Node(>7>)> >root.left.left.left>=> Node(>6>)> >root.left.left.left.left>=> Node(>5>)> >root>=> buildTree(root)> >print>(>'Preorder traversal of balanced BST is :'>)> >preOrder(root)> > # This code has been contributed by Vikash Kumar 37> |
의 이름
>
>
씨#
using> System;> using> System.Collections.Generic;> // C# program to convert a left unbalanced BST to a balanced BST> /* A binary tree node has data, pointer to left child> >and a pointer to right child */> public> class> Node> {> >public> int> data;> >public> Node left, right;> >public> Node(>int> data)> >{> >this>.data = data;> >left = right =>null>;> >}> }> public> class> BinaryTree> {> >public> Node root;> >/* This function traverse the skewed binary tree and> >stores its nodes pointers in vector nodes[] */> >public> virtual> void> storeBSTNodes(Node root, List nodes)> >{> >// Base case> >if> (root ==>null>)> >{> >return>;> >}> >// Store nodes in Inorder (which is sorted> >// order for BST)> >storeBSTNodes(root.left, nodes);> >nodes.Add(root);> >storeBSTNodes(root.right, nodes);> >}> >/* Recursive function to construct binary tree */> >public> virtual> Node buildTreeUtil(List nodes,>int> start,>int> end)> >{> >// base case> >if> (start>끝)> >{> >return> null>;> >}> >/* Get the middle element and make it root */> >int> mid = (start + end) / 2;> >Node node = nodes[mid];> >/* Using index in Inorder traversal, construct> >left and right subtress */> >node.left = buildTreeUtil(nodes, start, mid - 1);> >node.right = buildTreeUtil(nodes, mid + 1, end);> >return> node;> >}> >// This functions converts an unbalanced BST to> >// a balanced BST> >public> virtual> Node buildTree(Node root)> >{> >// Store nodes of given BST in sorted order> >List nodes =>new> List();> >storeBSTNodes(root, nodes);> >// Constructs BST from nodes[]> >int> n = nodes.Count;> >return> buildTreeUtil(nodes, 0, n - 1);> >}> >/* Function to do preorder traversal of tree */> >public> virtual> void> preOrder(Node node)> >{> >if> (node ==>null>)> >{> >return>;> >}> >Console.Write(node.data +>' '>);> >preOrder(node.left);> >preOrder(node.right);> >}> >// Driver program to test the above functions> >public> static> void> Main(>string>[] args)> >{> >/* Constructed skewed binary tree is> >10> >/> >8> >/> >7> >/> >6> >/> >5 */> >BinaryTree tree =>new> BinaryTree();> >tree.root =>new> Node(10);> >tree.root.left =>new> Node(8);> >tree.root.left.left =>new> Node(7);> >tree.root.left.left.left =>new> Node(6);> >tree.root.left.left.left.left =>new> Node(5);> >tree.root = tree.buildTree(tree.root);> >Console.WriteLine(>'Preorder traversal of balanced BST is :'>);> >tree.preOrder(tree.root);> >}> }> >// This code is contributed by Shrikant13> |
>
>
자바스크립트
숨겨진 앱
> >// JavaScript program to convert a left> >// unbalanced BST to a balanced BST> > >class Node> >{> >constructor(data) {> >this>.left =>null>;> >this>.right =>null>;> >this>.data = data;> >}> >}> > >let root;> > >/* This function traverse the skewed binary tree and> >stores its nodes pointers in vector nodes[] */> >function> storeBSTNodes(root, nodes)> >{> >// Base case> >if> (root ==>null>)> >return>;> > >// Store nodes in Inorder (which is sorted> >// order for BST)> >storeBSTNodes(root.left, nodes);> >nodes.push(root);> >storeBSTNodes(root.right, nodes);> >}> > >/* Recursive function to construct binary tree */> >function> buildTreeUtil(nodes, start, end)> >{> >// base case> >if> (start>끝)> >return> null>;> > >/* Get the middle element and make it root */> >let mid = parseInt((start + end) / 2, 10);> >let node = nodes[mid];> > >/* Using index in Inorder traversal, construct> >left and right subtress */> >node.left = buildTreeUtil(nodes, start, mid - 1);> >node.right = buildTreeUtil(nodes, mid + 1, end);> > >return> node;> >}> > >// This functions converts an unbalanced BST to> >// a balanced BST> >function> buildTree(root)> >{> >// Store nodes of given BST in sorted order> >let nodes = [];> >storeBSTNodes(root, nodes);> > >// Constructs BST from nodes[]> >let n = nodes.length;> >return> buildTreeUtil(nodes, 0, n - 1);> >}> > >/* Function to do preorder traversal of tree */> >function> preOrder(node)> >{> >if> (node ==>null>)> >return>;> >document.write(node.data +>' '>);> >preOrder(node.left);> >preOrder(node.right);> >}> > >/* Constructed skewed binary tree is> >10> >/> >8> >/> >7> >/> >6> >/> >5 */> >root =>new> Node(10);> >root.left =>new> Node(8);> >root.left.left =>new> Node(7);> >root.left.left.left =>new> Node(6);> >root.left.left.left.left =>new> Node(5);> >root = buildTree(root);> >document.write(>'Preorder traversal of balanced BST is :'> +>''>);> >preOrder(root);> > > |
>
>산출
Preorder traversal of balanced BST is : 7 5 6 8 10>
시간 복잡도: O(n), 우리는 트리를 두 번 순회합니다. 한 번은 중순 순회를 한 다음 균형 트리를 구성합니다.
보조 공간: O(n), 추가 공간은 중위 순회 노드를 벡터에 저장하는 데 사용됩니다. 또한 재귀 호출 스택이 차지하는 추가 공간은 O(h)입니다. 여기서 h는 트리의 높이입니다.
이 글은 기고되었습니다 아디트야 고엘 . techcodeview.com를 좋아하고 기여하고 싶다면 기사를 작성하여 [email protected]로 기사를 메일로 보낼 수도 있습니다.