一些必须要会的知识点:
树的遍历-递归-非递归-前序中序后序层序
前序遍历-非递归(栈)
void preOrder(treenode *root) {
if (root) {
stack<treenode *> st;
treenode *r =root;
while (!st.empty()||r) {
while (r) {
st.push(r);
cout << r->val;
r = r->left;
}
if (!st.empty()) {
r = st.top();
st.pop();
r = r->right;
}
}
}
}
void preOrder(treenode *root)
{
treenode * p = root;
stack<treenode*> S;
S.push(p);
while(!S.empty())
{
p = S.top();
S.pop();
cout<<p->data<<" ";
if(p->rchild)
S.push(p->rchild);
if(p->lchild)
S.push(p->lchild);
}
return ;
}
前序遍历-递归
void preOrder(treenode *root)
{
if(root)
{
cout<<root->data <<" ";
preOrder(root->lchild);
preOrder(root->rchild);
}
}
中序遍历-非递归(栈)
void inOrder(treenode *root) {
if (root) {
stack<treenode *> st;
treenode *r = root;
while (!st.empty() || r) {
while (r) {
st.push(r);
r = r->left;
}
if (!st.empty()) {
r = st.top();
cout << r->val;
st.pop();
r = r->right;
}
}
}
}
中序遍历-递归
void inOrder(treenode *root)
{
if(root)
{
inOrder(root->lchild);
cout<<root->data <<" ";
inOrder(root->rchild);
}
}
后序遍历-非递归(栈)
void postOrder(treenode *root) {
if (root) {
stack<treenode *> st;
treenode * r=root,*r=NULL;
while (r || !st.empty()) {
if (r) {
st.push(r);
r = r->left;
}
else {
r = st.top();
if(r->right!=NULL&&r->right != p){
r = r->right;
}
else {
st.pop();
cout << r->val;
p = r;
r = NULL;
}
}
}
}
}
后序遍历-递归
void postOrder(treenode* root)
{
if(root)
{
postOrder(root->lchild);
postOrder(root->rchild);
cout<<root->data <<" ";
}
}
层序遍历-非递归(队列)- LeetCode 求数的深度
class Solution {
public:
int TreeDepth(TreeNode* pRoot)
{
int res = 0;
if(pRoot==NULL)return res;
queue<TreeNode*> tq;
TreeNode* r = pRoot;
tq.push(r);
while(!tq.empty()){
int level_node_num = tq.size();
if(level_node_num!=0)res++;
while(level_node_num--){
r = tq.front();
cout<<r->val<<endl;
if(r->left!=NULL)tq.push(r->left);
if(r->right!=NULL)tq.push(r->right);
tq.pop();
}
}
return res;
}
};
包含min函数的栈
class Solution {
public:
stack<int>mins;
stack<int>data;
void push(int value) {
data.push(value);
if(mins.empty()){
mins.push(value);
}else{
if(value<mins.top()){
mins.push(value);
}else{
mins.push(mins.top());
}
}
}
void pop() {
if(data.empty()||mins.empty())return;
data.pop();
mins.pop();
}
int top() {
if(data.empty())return -1;
return data.top();
}
int min() {
return mins.top();
}
};
用两个栈实现队列
class Solution
{
private:
stack<int> stack1;
stack<int> stack2;
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if(stack1.empty()){
return -1;
}
while(!stack1.empty()){
stack2.push(stack1.top());
stack1.pop();
}
int res = stack2.top();
stack2.pop();
while(!stack2.empty()){
stack1.push(stack2.top());
stack2.pop();
}
return res;
}
};