-
[LeetCode] Convert Sorted Array to Binary Search Tree알고리즘 2019. 12. 4. 02:33
문제
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted array: [-10,-3,0,5,9], One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 0 / \ -3 9 / / -10 5
Approach
Sorting된 배열이므로 배열의 중앙값이 BST의 루트가 되고
이를 기준으로 왼쪽이 왼쪽 서브트리, 오른쪽이 오른쪽 서브트리가 된다.
그러므로 왼쪽 오른쪽을 다시 재귀를 통해 BST를 만들어 주면 됨
Code
https://github.com/chi3236/algorithm/blob/master/LeetCode_ConvertSortedArrayToBinarySearchTree.cpp
'알고리즘' 카테고리의 다른 글
[LeetCode] Pascal's Triangle (0) 2019.12.04 [LeetCode] Populating Next Right Pointers in Each Node (0) 2019.12.04 [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal (0) 2019.12.04 [LeetCode] Maximum Depth of Binary Tree (0) 2019.12.03 [LeetCode] Binary Tree Zigzag Level Order Traversal (0) 2019.12.02