?LeetCode刷題實戰(zhàn)109:有序鏈表轉換二叉搜索樹
Given the head of a singly linked list 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.
題意
解題
class?Solution?{
????public?TreeNode sortedListToBST(ListNode head) {
????????if(head == null) return?null;
????????return?createTree(head, null);
????}
????public?TreeNode createTree(ListNode head, ListNode tail) {
????????if(head == tail ) return?null;
????????ListNode fast = head;
????????ListNode slow = head;
????????while(fast != tail && fast.next != tail) {
????????????fast = fast.next.next;
????????????slow = slow.next;
????????}
????????TreeNode node = new?TreeNode(slow.val);
????????node.left = createTree(head, slow);
????????node.right = createTree(slow.next, tail);
????????return?node;
????}
}
好了,今天的文章就到這里,如果覺得有所收獲,請順手點個在看或者轉發(fā)吧,你們的支持是我最大的動力。
LeetCode刷題實戰(zhàn)102:二叉樹的層序遍歷
LeetCode刷題實戰(zhàn)103:二叉樹的鋸齒形層次遍歷
LeetCode刷題實戰(zhàn)104:二叉樹的最大深度
LeetCode刷題實戰(zhàn)105:從前序與中序遍歷序列構造二叉樹
