leetcode — convert-sorted-list-to-binary-search-tree
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
 * Source : https://oj.leetcode.com/problems/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.
 */
public class ConvertSortedList {
    /**
     * 将一个有序链表转化为一棵AVL树
     * 可以先把单向链表转化为有序数组,然后将数组转化为AVL树
     * 或者使用双指针,快指针每次移动两个位置,慢指针每次移动一个位置,这样就能找到中间的节点
     *
     * 还有一种方法:
     * 找到链表总个数total,一次递归如下:
     * 递归查找左子树,每次递归的时候将head指向下一个节点
     * 左子树递归完成之后,head指向了mid节点
     * 构造root节点,当前head指向的就是mid节点,也就是root节点
     * 递归构造右子树
     * 构造根节点,并返回
     *
     * @param head
     * @return
     */
    public TreeNode convert (ListNode head) {
        ListNode node = head;
        int total = 0;
        while (node != null) {
            total++;
            node = node.next;
        }
        return convert(new HeadHolder(head), 0, total-1);
    }
    /**
     * 因为每次递归需要改变head的值,所以使用一个HeadHolder指向head,每次修改headHolder的指向
     *
     * @param head
     * @param left
     * @param right
     * @return
     */
    public TreeNode convert (HeadHolder head, int left, int right) {
        if (left > right) {
            return null;
        }
        int mid = (left + right) / 2;
        TreeNode leftChild = convert(head, left, mid-1);
        // 上面递归完成之后,head指向了mid位置的节点
        TreeNode root = new TreeNode(head.head.value);
        // head的下一个节点就是右子树的第一个节点
        head.head = head.head.next;
        TreeNode rightChild = convert(head, mid+1, right);
        root.leftChild = leftChild;
        root.rightChild = rightChild;
        return root;
    }
    private class HeadHolder {
        ListNode head;
        public HeadHolder(ListNode head) {
            this.head = head;
        }
    }
    public ListNode createList (int[] arr) {
        if (arr.length == 0) {
            return null;
        }
        ListNode head = new ListNode();
        head.value = arr[0];
        ListNode pointer = head;
        for (int i = 1; i < arr.length; i++) {
            ListNode node = new ListNode();
            node.value = arr[i];
            pointer.next = node;
            pointer = pointer.next;
        }
        return head;
    }
    public void binarySearchTreeToArray (TreeNode root, List<Character> chs) {
        if (root == null) {
            chs.add('#');
            return;
        }
        List<TreeNode> list = new ArrayList<TreeNode>();
        int head = 0;
        int tail = 0;
        list.add(root);
        chs.add((char) (root.value + '0'));
        tail ++;
        TreeNode temp = null;
        while (head < tail) {
            temp = list.get(head);
            if (temp.leftChild != null) {
                list.add(temp.leftChild);
                chs.add((char) (temp.leftChild.value + '0'));
                tail ++;
            } else {
                chs.add('#');
            }
            if (temp.rightChild != null) {
                list.add(temp.rightChild);
                chs.add((char)(temp.rightChild.value + '0'));
                tail ++;
            } else {
                chs.add('#');
            }
            head ++;
        }
        //去除最后不必要的
        for (int i = chs.size()-1; i > 0; i--) {
            if (chs.get(i) != '#') {
                break;
            }
            chs.remove(i);
        }
    }
    private class TreeNode {
        TreeNode leftChild;
        TreeNode rightChild;
        int value;
        public TreeNode(int value) {
            this.value = value;
        }
        public TreeNode() {
        }
    }
    private class ListNode {
        ListNode next;
        int value;
        public ListNode(int value) {
            this.value = value;
        }
        public ListNode() {
        }
    }
    public static void main(String[] args) {
        ConvertSortedList convertSortedList = new ConvertSortedList();
        int[] arr = new int[]{1,2,3,4,5,6};
        List<Character> chs = new ArrayList<Character>();
        TreeNode root = convertSortedList.convert(convertSortedList.createList(arr));
        convertSortedList.binarySearchTreeToArray(root, chs);
        System.out.println(Arrays.toString(chs.toArray(new Character[chs.size()])));
    }
}
leetcode — convert-sorted-list-to-binary-search-tree的更多相关文章
- LeetCode:Convert Sorted Array to Binary Search Tree,Convert Sorted List to Binary Search Tree
		LeetCode:Convert Sorted Array to Binary Search Tree Given an array where elements are sorted in asce ... 
- Leetcode: Convert sorted list to binary search tree (No. 109)
		Sept. 22, 2015 学一道算法题, 经常回顾一下. 第二次重温, 决定增加一些图片, 帮助自己记忆. 在网上找他人的资料, 不如自己动手. 把从底向上树的算法搞通俗一些. 先做一个例子: 9 ... 
- [LeetCode]  Convert Sorted List to Binary Search Tree 将有序链表转为二叉搜索树
		Given a singly linked list where elements are sorted in ascending order, convert it to a height bala ... 
- [LeetCode] Convert Sorted Array to Binary Search Tree 将有序数组转为二叉搜索树
		Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 这道 ... 
- leetcode -- Convert Sorted List to Binary Search Tree
		Given a singly linked list where elements are sorted in ascending order, convert it to a height bala ... 
- 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 as ... 
- LeetCode: Convert Sorted Array to Binary Search Tree  解题报告
		Convert Sorted Array to Binary Search Tree Given an array where elements are sorted in ascending ord ... 
- LeetCode——Convert Sorted List to Binary Search Tree
		Given a singly linked list where elements are sorted in ascending order, convert it to a height bala ... 
- [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 bala ... 
- LeetCode——Convert Sorted Array to Binary Search Tree
		Description: Given an array where elements are sorted in ascending order, convert it to a height bal ... 
随机推荐
- bindservice与Activity通信
			package com.example.jikangwang.myapplication; import android.content.ComponentName; import android.c ... 
- 学习使用Mendeley1
			原文来自:https://www.mendeley.com/guides/desktop/01-desktop-interface 1.添加文件菜单 - 使用此功能将新条目添加到您的Mendeley库 ... 
- hadoop2-MapReduce详解
			本文是对Hadoop2.2.0版本的MapReduce进行详细讲解.请大家要注意版本,因为Hadoop的不同版本,源码可能是不同的. 以下是本文的大纲: 1.获取源码2.WordCount案例分析3. ... 
- 非vue-cli的花括号闪现问题
			<div id="app" v-cloak></div>[v-cloak] { display: none;}这种方式可以解决网速较慢,vue.js文件还没 ... 
- 异步使用委托delegate --- BeginInvoke和EndInvoke方法
			当我们定义一个委托的时候,一般语言运行时会自动帮委托定义BeginInvoke 和 EndInvoke两个方法,这两个方法的作用是可以异步调用委托. 方法BeginInvoke有两个参数: Async ... 
- LeetCode 单链表专题 (一)
			目录 LeetCode 单链表专题 <c++> \([2]\) Add Two Numbers \([92]\) Reverse Linked List II \([86]\) Parti ... 
- js 面向对象的三大特性:封装,继承、多态
			一:什么是封装? 封装的定义:就是对象内部的变化对外界是透明的,不可见的. 封装的场景: 在写项目的过程中,有时候不同页面,会有相同的功能,我们还需要每个页面都写一遍吗?额,,,,其实也可以写的,只不 ... 
- Could not resolve placeholder 'IMAGE_SERVER_URL' in string value "${IMAGE_SERVER_URL}"
			这种问题 在网上查的是说使用了重复的property-placeholder 可能是在别的xml 也用了property-placeholder 解决方法 加上 ignore-unresolva ... 
- Spring源码学习-容器BeanFactory(三) BeanDefinition的创建-解析Spring的默认标签
			写在前面 上文Spring源码学习-容器BeanFactory(二) BeanDefinition的创建-解析前BeanDefinition的前置操作中Spring对XML解析后创建了对应的Docum ... 
- vue变异方法
			push() 往数组最后面添加一个元素,成功返回当前数组的长度 pop() 删除数组的最后一个元素,成功返回删除元素的值 shift() 删除数组的第一个元素,成功返回删除元素的值u ... 
