zoukankan      html  css  js  c++  java
  • [LeetCode] Convert Sorted List to Binary Search Tree DFS,深度搜索

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

    Hide Tags
     Depth-first Search Linked List
     
        这题是将链表变成二叉树,比较麻烦的遍历过程,因为链表的限制,所以深度搜索的顺序恰巧是链表的顺序,通过设置好递归函数的参数,可以在深度搜索时候便可以遍历了。
     
    TreeNode * help_f(ListNode *&curList,int lft,int rgt)

    全部代码:

    #include <iostream>
    using namespace std;
    
    /**
     * Definition for singly-linked list.
     */
    struct ListNode {
        int val;
        ListNode *next;
        ListNode(int x) : val(x), next(NULL) {}
    };
    
    /**
     * Definitiosn 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) {
            int len=0;
            ListNode * p = head;
            while(p!=NULL){
                len++;
                p=p->next;
            }
    //        cout<<len<<endl;
            return help_f(head,0,len-1);
        }
    
        TreeNode * help_f(ListNode *&curList,int lft,int rgt)
        {
            if(lft>rgt) return  NULL;
            int mid=(lft+rgt)/2;
            TreeNode *lftCld = help_f(curList,lft,mid-1);
            TreeNode *parent =new TreeNode(curList->val);
            parent->left=lftCld;
            curList=curList->next;
            parent->right=help_f(curList,mid+1,rgt);
            return parent;
        }
    };
    
    int main()
    {
        ListNode n1(0);
        Solution sol;
        sol.sortedListToBST(&n1);
        return 0;
    }
  • 相关阅读:
    [转载]使用uiautomator做UI测试
    [转载]Android相关开发网站
    [转载]Android开发必备的21个免费资源和工具
    c# List集合的Find方法适用
    c# GridView Footor列求合计
    c# List集合排序
    mysql中插入多条记录-微软批处理
    mysql中插入多条记录-微软批处理
    VS2005快捷键
    LinqToSql 小例子
  • 原文地址:https://www.cnblogs.com/Azhu/p/4227191.html
Copyright © 2011-2022 走看看