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

    原题链接:https://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/

    题目:给定一个有正序链表,将其转换成一个二叉搜索树。

    思路:能够依照之前的数组的思路来做。即找到中间值。再左右递归建树。

    	public TreeNode sortedListToBST(ListNode head) {
    		if (head == null)
    			return null;
    		int len = 0;
    		ListNode tmp = head;
    		while (tmp != null) {
    			tmp = tmp.next;
    			len++;
    		}
    		return sortedListToBST(head, len);
    	}
    
    	public TreeNode sortedListToBST(ListNode head, int len) {
    		if (len <= 0)
    			return null;
    		int mid = (1 + len) / 2;
    		ListNode p = head;
    		int tmp = mid - 1;
    		while (tmp > 0) {
    			p = p.next;
    			tmp--;
    		}
    		TreeNode root = new TreeNode(p.val);
    		root.left = sortedListToBST(head, mid - 1);
    		root.right = sortedListToBST(p.next, len - mid);
    		return root;
    	}
    	// 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;
    		}
    	}


  • 相关阅读:
    TP框架对数据库的操作
    Nginx的安装及配置
    微信小程序的入门
    MySQL的多表联查
    Larave中CSRF攻击
    Linux(三)
    Linux(二)
    Linux(一)
    安全测试检查项
    mysql-视图及索引简介
  • 原文地址:https://www.cnblogs.com/lcchuguo/p/5396739.html
Copyright © 2011-2022 走看看