Problem
Given 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.
Example:
Given the sorted linked list: [-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 5Solution
class Solution { public TreeNode sortedListToBST(ListNode head) { return helper(head, null); } private TreeNode helper(ListNode head, ListNode tail) { if (head == tail) return null; ListNode fast = head, slow = head; while (fast != tail && fast.next != tail) { fast = fast.next.next; slow = slow.next; } TreeNode root = new TreeNode(slow.val); root.left = helper(head, slow); root.right = helper(slow.next, tail); return root; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/72186.html
摘要:題目要求給一個按照遞增順序排列的鏈表。將該鏈表轉化為平衡二叉樹。思路和代碼在這里需要注意的是,因為提供的數據結構為鏈表,所以我們必須順序遍歷才能知道該鏈表的長度以及該鏈表的中間位置。并依次遞歸左子節點和右子節點。 題目要求 Given a singly linked list where elements are sorted in ascending order, convert i...
摘要:我們可以用和兩個值來限定子樹在鏈表中的位置,通過遞歸的方式,深入找到最左邊,然后開始順序遍歷鏈表鏈表當前節點作為全局變量,這樣無論遞歸在哪我們都能拿到,同時建樹。代碼先遞歸的計算左子樹創造根節點最后遞歸的計算右子樹 Convert Sorted List to Binary Search Tree Given a singly linked list where elements ar...
摘要:題目答案這里是不能等于也省去了把從中間分隔時,需要添加的麻煩 題目:Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 答案: /** * Definition for singly-linked list. * p...
摘要:思路根據的性質,問題轉化為找一個里的中位數,用一個函數,一路找中點,再通過前序遍歷的方法把起來代碼 Convert Sorted Array to Binary Search Tree With Minimal Height Given a sorted (increasing order) array, Convert it to create a binarytree with m...
摘要:解題思路平衡二叉樹,其實就是數組中間的數作為根,利用遞歸實現左子樹和右子樹的構造。 Convert Sorted Array to Binary Search TreeGiven an array where elements are sorted in ascending order, convert it to a height balanced BST. 1.解題思路平衡二叉樹,...
閱讀 3686·2021-11-25 09:43
閱讀 2645·2021-11-25 09:43
閱讀 3844·2021-11-24 09:38
閱讀 697·2021-11-18 10:02
閱讀 2237·2021-09-22 15:53
閱讀 2998·2019-08-30 15:44
閱讀 2774·2019-08-30 14:01
閱讀 2754·2019-08-29 15:15