给定一个单链表,其中的元素按升序排序,请将它转化成平衡二叉搜索树(BST)
示例1
输入
{-1,0,1,2}
输出
{1,0,2,-1}
加载中...
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * } */ /* * public class ListNode { * int val; * ListNode next = null; * } */ public class Solution { /** * * @param head ListNode类 * @return TreeNode类 */ public TreeNode sortedListToBST (ListNode head) { // write code here } }
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ /** * struct ListNode { * int val; * struct ListNode *next; * }; */ class Solution { public: /** * * @param head ListNode类 * @return TreeNode类 */ TreeNode* sortedListToBST(ListNode* head) { // write code here } };
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # # @param head ListNode类 # @return TreeNode类 # class Solution: def sortedListToBST(self , head ): # write code here
/* * function TreeNode(x) { * this.val = x; * this.left = null; * this.right = null; * } */ /* * function ListNode(x){ * this.val = x; * this.next = null; * } */ /** * * @param head ListNode类 * @return TreeNode类 */ function sortedListToBST( head ) { // write code here } module.exports = { sortedListToBST : sortedListToBST };
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # # @param head ListNode类 # @return TreeNode类 # class Solution: def sortedListToBST(self , head ): # write code here
package main import . "nc_tools" /* * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ /* * type ListNode struct{ * Val int * Next *ListNode * } */ /** * * @param head ListNode类 * @return TreeNode类 */ func sortedListToBST( head *ListNode ) *TreeNode { // write code here }
{-1,0,1,2}
{1,0,2,-1}