zoukankan      html  css  js  c++  java
  • convert-sorted-list-to-binary-search-tree

    题目描述

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

    思路: https://siddontang.gitbooks.io/leetcode-solution/content/tree/convert_sorted_listarray_to_binary_search_tree.html
    //对于二叉树来说,左子树小于根节点,而右子树大于根结点。所以需要找到链表的中间节点,这个就是根节点。
    //链表的左半部分就是左子树,而右半部分是右子树,继续递归处理相应的左右部分,就可以构造对应的二叉树了。
    //难点在于如何找到链表的中间节点,可以通过fast、slow指针来解决,fast走两步,slow每次走一步,fast走到尾,slow就是中间节点。

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        TreeNode *sortedListToBST(ListNode *head) {
            return build(head,NULL);
        }
        TreeNode *build(ListNode *start,ListNode *end) {
            if(start==end) {
                return NULL;
            }
            ListNode *fast=start;
            ListNode *slow=start;
            while(fast!=end &&fast->next!=end) {
                fast=fast->next->next;
                slow=slow->next;
            }
            TreeNode *node=new TreeNode(slow->val);
            node->left=build(start,slow);
            node->right=build(slow->next,end);
            return node;
        }
    };
    

      

    拥抱明天! 不给自己做枷锁去限制自己。 别让时代的悲哀,成为你人生的悲哀。
  • 相关阅读:
    设计模式面试
    Netty面试
    Nginx面试
    java后端面试
    springboot面试专题及答案
    SpringBoot整合Mybatis,TypeAliases配置失败的问题
    vscode调试html文件
    Linux性能检查命令总结[转]
    如何创建systemd定时任务
    Systemd简介与使用
  • 原文地址:https://www.cnblogs.com/dd2hm/p/7507223.html
Copyright © 2011-2022 走看看