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.

    用空间换时间的方法,先用一个数组将节点按序存放,然后建树,代码如下:

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; next = null; }
     * }
     */
    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        
        private List<TreeNode> list = new ArrayList<TreeNode>();
        
        public TreeNode creatBST(int low,int high) {
            if(low<=high) {
                int mid = (high+low)/2;
                TreeNode root = list.get(mid);
                root.left = creatBST(low,mid-1);
                root.right = creatBST(mid+1,high);
                return root;
            }
            else return null;
          
        }
        
        public TreeNode sortedListToBST(ListNode head) {
            while(head!=null) {
                TreeNode node = new TreeNode(head.val);
                list.add(node);
                head = head.next;
            }
            return creatBST(0,list.size()-1);
    
        }
    }
  • 相关阅读:
    allocator类
    智能指针shared_ptr
    字面值常量类
    转换构造函数
    委托构造函数
    访问说明符&封装
    const成员函数
    函数指针
    constexper和常量表达式
    函数返回数组指针
  • 原文地址:https://www.cnblogs.com/mrpod2g/p/4415692.html
Copyright © 2011-2022 走看看