Convert Sorted List to Binary Search Tree ------C++ 递归创建平衡二叉查找树

有序链表

0->1->2->3->4->5

转换为一个二叉排序树。我们在此创建一个平衡二叉排序树

1.先找链表到中间的节点

2.中间节点的val创建一个新的树节点TreeNode

3.将链表断裂为2部分

4.递归创建左子树和右子树

#include<iostream> #include<cstdlib>

using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: TreeNode* sortedListToBST(ListNode* head) { //如果节点为空直接返回空指针

        if(head==NULL){ return NULL; } //创建新节点,返回

        if(head->next==NULL){ TreeNode * root; root=new TreeNode(head->val); return root; } //只有2个节点,取第一个作为根节点,第2个作为右节点

        if(head->next->next==NULL){ TreeNode * root; root=new TreeNode(head->val); TreeNode * right; right=new TreeNode(head->next->val); root->right=right; return root; } //找到中间节点

        ListNode *step1,*step2; step1=head; step2=head; ListNode *temp;//保存中间节点的前一个节点

        while(step2->next!=NULL&&step2->next->next!=NULL){ temp=step1; step1=step1->next; step2=step2->next->next; } temp->next=NULL;//将链表在中间断开 //创建新的根节点

        TreeNode *root ; root=new TreeNode(step1->val); //递归创建左右子树

        TreeNode *left,*right; left=sortedListToBST(head); right=sortedListToBST(step1->next); root->left=left; root->right=right; return root; } }; class Travel{ public: void travel(TreeNode * root){ if(root==NULL){ return ; } //cout<<root->val<<endl;//先序遍历

        travel(root->left); //cout<<root->val<<endl;//中序遍历

        travel(root->right); //cout<<root->val<<endl;//后续遍历

 } }; main(){ ListNode *head,*tail; head=new ListNode(0); tail=head; for(int i=1;i<6;i++){ ListNode *temp; temp=new ListNode(i); tail->next=temp; tail=tail->next; } Solution s; TreeNode *root; root=s.sortedListToBST(head); Travel t; t.travel(root); }

ps:送一个遍历小程序

你可能感兴趣的:(Binary search)