• 【leetcode】Convert Sorted List to Binary Search Tree


    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.

     
     
    可以采用类似于Covert Sorted Array to Binary Search Tree的方法,但是寻找中点对于链表来说效率较低
    可以采用更高效的递归方式,无需寻找中点
    注意引用传递:TreeNode *buildTree(ListNode *&node,int left,int right)
     
     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 /**
    10  * Definition for binary tree
    11  * struct TreeNode {
    12  *     int val;
    13  *     TreeNode *left;
    14  *     TreeNode *right;
    15  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    16  * };
    17  */
    18 class Solution {
    19 public:
    20     TreeNode *sortedListToBST(ListNode *head) {
    21        
    22         ListNode *p=head;
    23         int len=0;
    24         while(p!=NULL)
    25         {
    26             p=p->next;
    27             len++;
    28         }
    29        
    30         TreeNode * root=buildTree(head,0,len-1);
    31         return root;
    32        
    33     }
    34    
    35    
    36     TreeNode *buildTree(ListNode *&node,int left,int right)
    37     {
    38         if(left>right) return NULL;
    39        
    40         int mid=(left+right)/2;
    41        
    42         TreeNode *leftTree=buildTree(node,left,mid-1);
    43         TreeNode *root=new TreeNode(node->val);
    44         node=node->next;
    45         TreeNode *rightTree=buildTree(node,mid+1,right);
    46         root->left=leftTree;
    47         root->right=rightTree;
    48         return root;
    49     }
    50    
    51 };
  • 相关阅读:
    git 远程仓库的使用
    git 以及 工作区 版本库 暂存区
    git repo gerrit 的关系
    【转】c# delegate
    【转】分析.net中的object sender与EventArgs e
    如果plsql连接没问题,但程序中报ORA-12504的错误
    【转】C# String 与 Char[] 数组 相互转换
    【转】C#日期时间格式化
    PLSQL导出语句的查询结果
    oracle取order by的第一条数据
  • 原文地址:https://www.cnblogs.com/reachteam/p/4216420.html
Copyright © 2020-2023  润新知