数组生成MaxTree——C++
2016-02-24 18:42
253 查看
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; }`
相关文章推荐
- 《孙鑫vc++视频20集》【最后更新日期:16/04/20
- C++的一些注意事项
- C/C++ 中嵌入 arm 汇编
- C++学习笔记:虚析构函数
- 1038. Recover the Smallest Number (30)
- C++除法取整
- 汉诺塔与递归之C++ 和Python实现
- [C&C++]用WinSock封装自己的UDP类2
- C文件管理学习心得
- 实例讲解C++编程中的虚函数与虚基类
- 1037. Magic Coupon (25)
- 理解C++里面的const的一些用法
- 1036. Boys vs Girls (25)
- C++开发基础整理
- C语言实现链表的基本操作
- C语言基础整理
- C++基础::字符串流(stringstream)
- 统计文件目录下所有文件个数并打印文件名
- 1035. Password (20)
- 2、构造、析构和赋值运算