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.


用遞歸的方法:

    n=0:返回Null

    n≠0:先對左子樹進行構造,再對根節點進行構造,最後對右子樹進行構造。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
	TreeNode* generate(int n)
	{
		if (n==0)
		{
			return NULL;
		}
		TreeNode *node = new TreeNode(0);
		node->left = generate(n/2);                  //先構造左子樹
		node->val = list->val;                       //構造中節點
		list = list->next;                           //鏈表推進
		node->right = generate(n-n/2-1);             //構造右子樹
		return node;
	}
    TreeNode* sortedListToBST(ListNode* head) {
        int size = 0;
        this->list = head;
        while(head!=NULL)
        {
        	++size;
        	head = head->next;
        }
        return generate(size);
    }
private:
	ListNode *list;
};


發佈了73 篇原創文章 · 獲贊 11 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章