classMinStack{public:/** initialize your data structure here. */MinStack(){}voidpush(int x){left.push(x);int min;if(!right.empty()&& right.top()<= x){min = right.top();}else{min = x;}right.push(min);}voidpop(){left.pop();right.pop();}inttop(){return left.top();}intgetMin(){return right.top();}stack<int> left;//存正长的数据stack<int> right;//存最小的数据};
优化版本
classMinStack{public:/** initialize your data structure here. */MinStack(){}voidpush(int x){left.push(x);if(right.empty()|| x <= right.top()){right.push(x);}}voidpop(){int top = left.top();//先让左边出栈并记录元素left.pop();if(top == right.top()){//如果左边出栈得元素等于右边栈顶元素,右边才出right.pop();}}inttop(){return left.top();}intgetMin(){return right.top();}stack<int> left;//存正长的数据stack<int> right;//存最小的数据};
再写循环队列 class MyCircularQueue {
public:/** Initialize your data structure here. Set the size of the queue to be k. */MyCircularQueue(int k) {array (int *)malloc(sizeof(int)*k);capacity k;size 0;front 0;rear 0;}/** Insert an element into the circu…
前序遍历 /*** Definition for a binary tree node.* struct TreeNode {* int val;* struct TreeNode *left;* struct TreeNode *right;* };*//*** Note: The returned array must be malloced, assume caller calls free().*/
int *array;
int size;void _preorde…
平衡二叉树 /*** Definition for a binary tree node.* struct TreeNode {* int val;* struct TreeNode *left;* struct TreeNode *right;* };*/int MAX(int a,int b)
{return a > b ? a : b;
}//求高度
int getHeight(struct TreeNode *root){if(root NULL){…
前序中序遍历构造二叉树 思路
在前序中找根结点根据根结点 中序,分成左右两棵子树根据子树长度,把前序分成左右两颗子树递归处理子树
/*** Definition for a binary tree node.* struct TreeNode {* int val;* struct TreeNode *left;* s…