题目:Given the head
of a singly linked list where elements are sorted in ascending order,convert it to a height-balanced binary search tree.
constraints: The number of nodes in head is in the range [0, 20000]; -100000 <= Node.val <= 100000
思路:1、题目输入项为升序单向链表,可视为高度平衡的二叉搜索树中序遍历结果; 2、期望结果为高度平衡的二叉搜索树,平衡二叉树要求任意一个节点的左右子树高度相差不能大于1,可计算链表长度后还原树结构,返回根节点;
解答:中序遍历,还原树的生成过程。设计function1:左子树向上生长及调用function2;设计function2:生成右子树及连接到当前根节点。 思路还比较简单,留意下边界条件和方法参数就行。提交后时间复杂度尚可,空间复杂度有空再优化下。
附代码(Java):
private static ListNode treeNode = null; private static int leftLeaf = 1, rightLeaf = 1; public static TreeNode sortedListToBST(ListNode head) { if (head == null) return null; TreeNode child = new TreeNode(head.val); treeNode = head; int length = 1; treeNode = treeNode.next; while (treeNode != null) { ++length; treeNode = treeNode.next; } treeNode = head.next; //reset int bstHeight = 1; leftLeaf = length - 1; while (leftLeaf > 0) { //计算层数及叶子节点个数 rightLeaf = rightLeaf * 2; leftLeaf = leftLeaf - rightLeaf; ++bstHeight; } leftLeaf += rightLeaf; //叶子节点总数 rightLeaf = (leftLeaf - rightLeaf / 2 > 0 ? leftLeaf - rightLeaf / 2 : 0); leftLeaf = leftLeaf - rightLeaf; //根据已得中序遍历树元素和树结构(层数,叶子节点排列)还原树; if (bstHeight == 1) return child; //bstLayer>1 child = function1(child, bstHeight); return child; } private static TreeNode function1(TreeNode child, int height) { //隐性条件:h>1 int h = 1; while (h < height) { TreeNode root = new TreeNode(treeNode.val); root.left = child; treeNode = treeNode.next; function2(root, h); child = root; ++h; } return child; } private static void function2(TreeNode father, int height) { //集成对leftLeaf,rightLeaf的判断,子树高度=1时判断rightLeaf,>1时判断leftLeaf if (height > 1) { TreeNode left = null; if (leftLeaf > 0) { --leftLeaf; left = new TreeNode(treeNode.val); treeNode = treeNode.next; } TreeNode right = function1(left, height); father.right = right; } else { if (rightLeaf > 0) { --rightLeaf; TreeNode right = new TreeNode(treeNode.val); father.right = right; treeNode = treeNode.next; } else return; } }