Leetcode 109.Convert sorted list to BST

题目: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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值