赞
踩
难度:中等
给定一个单链表的头节点 head ,其中的元素 按升序排序 ,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差不超过 1。
输入: head = [-10,-3,0,5,9]
输出: [0,-3,9,-10,null,5]
解释: 一个可能的答案是[0,-3,9,-10,null,5],它表示所示的高度平衡的二叉搜索树。
输入: head = []
输出: []
和 0108一样的思路,将链表中的元素转存到数组中,之后按照 0108 的思路解题即可
using System; using System.Collections; using System.Collections.Generic; public class ListNode { public int val; public ListNode next; public ListNode(int val = 0, ListNode next = null) { this.val = val; this.next = next; } } public class TreeNode { public int val; public TreeNode left; public TreeNode right; public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null) { this .val = val; this.left = left; this.right = right; } } class Solution { public static void Main(string[] args) { ListNode list = new ListNode { val = -10, next = new ListNode { val = -3, next = new ListNode { val = 0, next = new ListNode { val = 5, next = new ListNode { val = 9 } } } } }; Solution solution = new Solution(); TreeNode ans = solution.SortedListToBST(list); Console.ReadKey(); } public TreeNode SortedListToBST(ListNode head) { Queue<int> queue = new Queue<int>(); int index = 0; while (head != null) { queue.Enqueue(head.val); head = head.next; } int[] temp = new int[queue.Count]; while (queue.Count > 0) { temp[index] = queue.Dequeue(); index++; } return BackTrack(temp, 0, temp.Length - 1); } public TreeNode BackTrack(int[] nums, int start, int end) { if (start > end) { return null; } int mid = (start + end) / 2; return new TreeNode(nums[mid], BackTrack(nums, start, mid - 1), BackTrack(nums, mid + 1, end)); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。