Convert Sorted List to Binary Search Tree ------C++ 递归创建平衡二叉查找树
2015-06-03 20:26
489 查看
有序链表
0->1->2->3->4->5
转换为一个二叉排序树。我们在此创建一个平衡二叉排序树
1.先找链表到中间的节点
2.中间节点的val创建一个新的树节点TreeNode
3.将链表断裂为2部分
4.递归创建左子树和右子树
ps:送一个遍历小程序
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:送一个遍历小程序
相关文章推荐
- 黑马程序员——C语言基础——结构体以及结构体指针实战
- C++环形矩阵填充实现
- c++ 时间类型详解 time_t
- C/C++中extern关键字详解
- C语言指针的初始化和赋值
- 【Minimum Path Sum】cpp
- C语言中的union用法
- 12个有趣的C语言面试题
- C语言中的enum(枚举)用法
- poj1258_prime
- C++:模板
- C语言中对大文件操作遇到的问题
- 动作手游源码分析3 classes/layer/GameHeroLayer.cpp
- C++实现费马小定理素数测试
- 笔记---c++ primer——struct(一)
- C/C++中各种数据类型 如 int ,char long,double 的范围(最大值和最小值)
- poj1258_kruskal
- 【学习笔记】【C语言】自增自减
- C语言笔记
- C语言:全局变量在多个c文件中公用的方法