数组生成MaxTree——C++
来源:互联网 发布:高收益网络国债信托 编辑:程序博客网 时间:2024/06/03 07:50
MaxTree
`class node{ public: int value; node() { left = NULL; right = NULL; } ~node(){}; node( int val ) { value = val; left = NULL; right = NULL; } node *left,*right;};node* maxTree( int* array,int length ,node* nArr){ if ( !array || length<=0) { return NULL; } nArr = new node[length]; for (int i = 0 ; i < length; i++) { nArr[i] = node(array[i]); } node** leftmax = new node*[length]; node** rightmax = new node*[length]; // 左边最近、最大的值 std::stack<node*> nstack; for ( int i =0; i < length; i++ ) { while ( !nstack.empty() ) { if ( nArr[i].value >= nstack.top()->value ) { nstack.pop(); } else { leftmax[i] = nstack.top(); break; } } if ( nstack.empty() ) { leftmax[i] = NULL; } nstack.push(&nArr[i]); } while ( !nstack.empty() ) { nstack.pop(); } // 右边最近、最大的值 for ( int i =length-1; i >= 0; i-- ) { while ( !nstack.empty() ) { if ( nArr[i].value >= nstack.top()->value ) { nstack.pop(); } else { node temp = *nstack.top(); rightmax[i] = nstack.top(); break; } } if ( nstack.empty() ) { rightmax[i] = NULL; } nstack.push(&nArr[i]); } //建立树 node* head; for ( int i = 0; i < length; i++ ) { if ( !leftmax[i] && !rightmax[i] )//左右两边都没有最大值 { head = &nArr[i]; } else if ( !leftmax[i] )//最大值在右边 { if ( !rightmax[i]->left ) rightmax[i]->left = &nArr[i]; else rightmax[i]->right = &nArr[i]; } else if ( !rightmax[i] )//最大值在左边 { if ( !leftmax[i]->left ) leftmax[i]->left = &nArr[i]; else leftmax[i]->right = &nArr[i]; } else //左右都有最大值,比较那个值小 { node* parent = (leftmax[i]->value > rightmax[i]->value)? rightmax[i] : leftmax[i]; if ( !parent->left ) { parent->left = &nArr[i]; } else { parent->right = &nArr[i]; } } } delete [] leftmax; delete [] rightmax; return head;}`
0 0
- 数组生成MaxTree——C++
- 那些年我们刷过的算法题——输入数组构建MAXtree
- 栈和队列——构造数组的MaxTree(java实现)
- 数组变MaxTree-java
- 构造数组的MaxTree
- 构造数组的MaxTree
- 构造数组的MaxTree
- 构造数组的MaxTree
- 【算法】构造数组的MaxTree
- MaxTree
- 【难】【二叉树】构造数组的MaxTree
- 数据结构(8) 构造数组的MaxTree
- 1_8构造数组的maxtree
- 构造数组的MaxTree----详细的题解
- 栈和队列---构造数组的MaxTree
- 构造数组的MaxTree(二叉树)
- 栈和队列 构造数组的MaxTree
- 建立数组的MaxTree + 栈 + HashMap + 二叉树的建立
- 我们编程吧 之 Linux 学习手册0.41
- hadoop面试题
- 快速排列(传说中的快排)
- Masonry 到底有多美?(下)
- javaScript学习笔记(三)
- 数组生成MaxTree——C++
- FILE文件流的中fopen、fread、fseek、fclose的使用
- 八大排序法
- 彻底删除nginx
- 10步让你成为更优秀的程序员
- Spring AOP与IOC以及自定义注解
- arm9+linux fl2440 led 驱动 plat_led.c
- 点击导航下的某个栏目,出现在相应区域;滚动到某个区域,导航下的某个栏目相应效果
- UIFont字体大全