资讯专栏INFORMATION COLUMN

109. Converted Sorted List to Binary Search Tree

plokmju88 / 3121人阅读

摘要:题目答案这里是不能等于也省去了把从中间分隔时,需要添加的麻烦

题目:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

答案:

</>复制代码

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. /**
  10. * Definition for a binary tree node.
  11. * public class TreeNode {
  12. * int val;
  13. * TreeNode left;
  14. * TreeNode right;
  15. * TreeNode(int x) { val = x; }
  16. * }
  17. */
  18. public class Solution {
  19. public TreeNode BST(ListNode head, ListNode tail) {
  20. ListNode slow = head, fast = head;
  21. if (head == tail) return null;
  22. //这里是fast不能等于tail,也省去了把listnode从中间分隔时,需要添加null的麻烦!
  23. while (fast != tail && fast.next != tail) {
  24. slow = slow.next;
  25. fast = fast.next.next;
  26. }
  27. TreeNode root = new TreeNode(slow.val);
  28. root.left = BST(head, slow);
  29. root.right = BST(slow.next, tail);
  30. return root;
  31. }
  32. public TreeNode sortedListToBST(ListNode head) {
  33. if (head == null) return null;
  34. return BST(head, null);
  35. }
  36. }

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/64921.html

相关文章

  • leetcode109. Convert Sorted List to Binary Search

    摘要:题目要求给一个按照递增顺序排列的链表。将该链表转化为平衡二叉树。思路和代码在这里需要注意的是,因为提供的数据结构为链表,所以我们必须顺序遍历才能知道该链表的长度以及该链表的中间位置。并依次递归左子节点和右子节点。 题目要求 Given a singly linked list where elements are sorted in ascending order, convert i...

    高胜山 评论0 收藏0
  • [LeetCode] 109. Convert Sorted List to Binary Sear

    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 whi...

    dongfangyiyu 评论0 收藏0
  • 前端 | 每天一个 LeetCode

    摘要:在线网站地址我的微信公众号完整题目列表从年月日起,每天更新一题,顺序从易到难,目前已更新个题。这是项目地址欢迎一起交流学习。 这篇文章记录我练习的 LeetCode 题目,语言 JavaScript。 在线网站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公众号: showImg(htt...

    张汉庆 评论0 收藏0
  • leetcode部分题目答案之JavaScript版

    摘要:自己没事刷的一些的题目,若有更好的解法,希望能够一起探讨项目地址 自己没事刷的一些LeetCode的题目,若有更好的解法,希望能够一起探讨 Number Problem Solution Difficulty 204 Count Primes JavaScript Easy 202 Happy Number JavaScript Easy 190 Reverse Bi...

    alphahans 评论0 收藏0
  • [Leetcode] Convert Sorted Array/List to Binary Sea

    摘要:我们可以用和两个值来限定子树在链表中的位置,通过递归的方式,深入找到最左边,然后开始顺序遍历链表链表当前节点作为全局变量,这样无论递归在哪我们都能拿到,同时建树。代码先递归的计算左子树创造根节点最后递归的计算右子树 Convert Sorted List to Binary Search Tree Given a singly linked list where elements ar...

    wpw 评论0 收藏0

发表评论

0条评论

plokmju88

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<