程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> LeetCode -- Convert SortedList To BST

LeetCode -- Convert SortedList To BST

編輯:C++入門知識

LeetCode -- Convert SortedList To BST


 


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


就是把鏈表轉化為二叉查找樹


思路:
使用分治策略
1.把鏈表節點遍歷,存在nodes集合中
2.用[0, length/2)節點創建左子樹,用(length/2,n]節點創建右子樹,使用nodes[length/2]來創建當前節點。




實現代碼:




/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) { val = x; }
 * }
 */
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode SortedListToBST(ListNode head) {
        if(head == null){
		return null;
	}
	
	var nodes = new List();
	while(head != null){
		nodes.Add(head.val);
		head = head.next;
	}
	
	TreeNode root = null;
	BuildTree(nodes,ref root);
	
	return root;
}


private void BuildTree(IList values,ref TreeNode n){
	if(values.Count == 0){
		return;
	}


	var mid = (int)(values.Count/2);
	var self = values[mid];
	n = new TreeNode(self);
	
	var leftVals=  values.Where(x=>x < self);
	var rightVals = values.Where(x=>x > self);
	
	if(leftVals.Any()){
		BuildTree(leftVals.ToList() ,ref n.left);
	}
	if(rightVals.Any()){
		BuildTree(rightVals.ToList(),ref n.right);
	}
}




}


 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved