leetcode_109_有序链表转平衡二叉树_二分法

这几天的题目都不难,所以几天没记录博客2333333333。这个题目难度中等,想到了就比较简单。。。


题目:

给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。

本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


思路:

//    建立完全二叉树。二分法
//    每次都找到List[s:e)的中间位置 p 作为当前树的根,
//    然后同样的方式递归处理List[s:p)和List[p.next:e)。
//    不是很难

实现:(再次体会C++的高速。。。Python还是一如既往的速度慢2333)

JAVA版:

package leetcode;

import java.util.LinkedList;

/*
USER:LQY
DATE:2020/8/18
TIME:8:43
*/
public class leetcode_109 {

    public static void main(String[] args){

    }
//    建立完全二叉树。二分法
//    每次都找到List[s:e)的中间位置 p 作为当前树的根,
//    然后同样的方式递归处理List[s:p)和List[p.next:e)。
//    不是很难
    public TreeNode sortedListToBST(ListNode head) {
        if(head == null) return null;
        int size = 0;
        ListNode p = head;

//        先处理第一个根,特殊处理
//        计数

        while(p != null){
            size++;
            p = p.next;
        }
        if(size == 1){
            return new TreeNode(head.val);
        }
        int index = 0;
        p = head;
//      找到中间值
        while(index<size/2 && p!=null){
            index++;
            p = p.next;
        }
        TreeNode root = new TreeNode(p.val);
//        再处理[s,p)与[p.next, e)。
//        处理一样,只是要递归处理所以另外开辟一个函数。
        solve(root, head, p, -1);
        solve(root, p.next, null, 1);

        return root;
    }
//    flag = 1表示找到的 p 放到当前root的右子树。
//    flag = -1则放到root的左子树
//  这个函数还可以改进一下:增加一个每一段长度的参数,就可以免除下面的对[s, e)的计数。
    void solve(TreeNode root, ListNode s, ListNode e, int flag){
        if(root==null || s==null || s==e) return;
        int size = 0;
        ListNode p = s;
        while(p != e){
            size++;
            p = p.next;
        }
//        if(size == 0) return;

        p = s;
        int index = 0;
        while(index<size/2 && p!=null){
            index++;
            p = p.next;
        }
        switch(flag){
            case -1:
                root.left = new TreeNode(p.val);
                solve(root.left, s, p, -1);
                solve(root.left, p.next, e, 1);
                break;
            default:
                root.right = new TreeNode(p.val);
                solve(root.right, s, p, -1);
                solve(root.right, p.next, e, 1);
        }

    }

    class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
    }
    class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
}

C++版:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedListToBST(ListNode* head) {
        if(head == NULL) return NULL;
        //处理第一个[head, null)
        // 先zh
        int size = 0;
        ListNode *p = head;

        while(p != NULL){
            size++;
            p = p->next;
        }
        if(size == 1) return new TreeNode(head->val);

        int index = 0;
        p = head;
        while(index<size/2 && p!=NULL){
            index++;
            p = p->next;
        }
        TreeNode *root = new TreeNode(p->val);
        solve(root, head, p, -1);
        solve(root, p->next, NULL, 1);

        return root;

    }
    void solve(TreeNode *root, ListNode *s, ListNode *e, int flag){
        if(root==NULL || s==e || s==NULL) return;

        int size = 0;
        ListNode *p = s;
        while(p != e){
            size++;
            p = p->next;
        }
        p = s;
        int index = 0;
        while(index<size/2 && p!=NULL){
            index++;
            p = p->next;
        }
        switch(flag){
            case -1:
                root->left = new TreeNode(p->val);
                solve(root->left, s, p, -1);
                solve(root->left, p->next, e, 1);
                break;
            default:
                root->right = new TreeNode(p->val);
                solve(root->right, s, p, -1);
                solve(root->right, p->next, e, 1);
        }
    }
};

Python版:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def sortedListToBST(self, head: ListNode) -> TreeNode:

        def solve(root: TreeNode, s: ListNode, e: ListNode, flag: int):
            if root==None or s==e or s==None:
                return

            size = 0
            p = s
            while p != e:
                size += 1
                p = p.next
            p = s
            index = 0
            while index < size//2:
                index += 1
                p = p.next

            if flag == -1:
                root.left = TreeNode(p.val)
                solve(root.left, s, p, -1)
                solve(root.left, p.next, e, 1)

            else:
                root.right = TreeNode(p.val)
                solve(root.right, s, p, -1)
                solve(root.right, p.next, e, 1)



        if head == None:
            return None

        size = 0
        p = head
        while p != None:
            size += 1
            p = p.next

        p = head
        index = 0
        while index < size//2:
            index += 1
            p = p.next

        root = TreeNode(p.val)
        solve(root, head, p, -1)
        solve(root, p.next, None, 1)

        return root

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值