[LeetCode] 109番号付きリストのバイナリ検索ツリーを変換します

トピックへのリンク:https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree/

件名の説明:

バランスのとれたバイナリ検索ツリーに変換するために、要素が昇順にソートされた前記一重リンクリストを、与えられました。

この問題において、非常にバランスの取れた二分木は、二分木は、各ノードの左及び右サブツリーを指すことは、1以上ではないの絶対値との間の高さの差です。

例:

给定的有序链表: [-10, -3, 0, 5, 9],

一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:

      0
     / \
   -3   9
   /   /
 -10  5

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

アイデア:

そして、前の質問108は、二分探索木の秩序配列に変換、または中間点を見つけます

しかし、これは中間点を見つけるためのリストであるので、我々は、ポインタの速度を使用しました!

コード:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def sortedListToBST(self, head: ListNode) -> TreeNode:
        def findmid(head, tail):
            slow = head
            fast = head
            while fast != tail and fast.next!= tail :
                slow = slow.next
                fast = fast.next.next
            return slow
        
        def helper(head, tail):
            if  head == tail: return 
            node = findmid(head, tail)
            root = TreeNode(node.val)
            root.left = helper(head, node)
            root.right = helper(node.next, tail)
            return root
            
        return helper(head, None)
            

ジャワ

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
   public TreeNode sortedListToBST(ListNode head) {
        if (head == null) return null;
        return helper(head, null);

    }

    private TreeNode helper(ListNode head, ListNode tail) {
        if (head == tail) return null;
        // mid
        ListNode slow = head;
        ListNode fast = head;
        while (fast != tail && fast.next != tail) {
            slow = slow.next;
            fast = fast.next.next;
        }
        TreeNode root = new TreeNode(slow.val);
        root.left = helper(head, slow);
        root.right = helper(slow.next, tail);
        return root;
    }
}

おすすめ

転載: www.cnblogs.com/powercai/p/11104608.html