zoukankan      html  css  js  c++  java
  • 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.

    思路:

      典型的dfs思路

    我的代码:

    public class Solution {
        public TreeNode sortedListToBST(ListNode head) {
            if(head == null)    return null;
            if(head.next == null) return new TreeNode(head.val);
            ListNode dummy = new ListNode(-1);
            dummy.next = head;
            ListNode mid = getMiddle(head, dummy);
            TreeNode root = new TreeNode(mid.val);
            TreeNode left = sortedListToBST(dummy.next);
            TreeNode right = sortedListToBST(mid.next);
            root.left = left;
            root.right = right;
            return root;
        }
        public ListNode getMiddle(ListNode head, ListNode dummy)
        {
            ListNode pre = dummy;
            ListNode slow = head;
            ListNode fast = head.next;
            while(fast != null && fast.next != null)
            {
                slow = slow.next;
                fast = fast.next.next;
                pre = pre.next;
            }
            pre.next = null;
            return slow;
        }
    }
    View Code
  • 相关阅读:
    sql--删除
    数据库--范式
    sql语句--插入
    sql--查询
    shapefile数据文件组成
    sql---应用
    sql语句 函数
    SWIG:Simple Wrapper and Interface Generator
    职责链模式
    mybatis 装饰模式【Executor】 缓存篇
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4335596.html
Copyright © 2011-2022 走看看