前中后层序遍历的迭代和递归实现
前:中间节点最先处理;
中:中间节点在中间处理;
后:中间节点在最后处理;
void preOrder(node* root, vector<int>& p_vec)
{
stack<node*> p_sta;
if(root) p_sta.push(root);
while (!p_sta.empty())
{
//从栈中获取元素放入数组,然后出栈
node* cur = p_sta.top();
p_vec.push_back(cur->data);
p_sta.pop();
if (cur->right) p_sta.push(cur->right);
if (cur->left) p_sta.push(cur->left);
}
}
void inOrder(node* root, vector<int>& vec)
{
stack<node*> in_sta;
node* cur = root;
while (cur != nullptr || !in_sta.empty())
{
//一直循环找到以一个结点开始的最左结点
while (cur != nullptr)
{
in_sta.push(cur);
cur = cur->left;
}
//找到了
node* leftNode = in_sta.top();
in_sta.pop();
vec.push_back(leftNode->data);
//因为中序遍历,遍历完最左结点,就应该是这个结点的右节点了
cur = leftNode->right;
}
}
void postOrder(node* root,vector<int>& p_vec)
{
stack<node*> p_sta;
if(root) p_sta.push(root);
while (!p_sta.empty())
{
//从栈中获取元素放入数组,然后出栈
node* cur = p_sta.top();
p_vec.push_back(cur->data);
p_sta.pop();
if (cur->left) p_sta.push(cur->left);
if (cur->right) p_sta.push(cur->right);
}
reverse(p_vec.begin(),p_vec.end());
}
void levelOrder(node* root, vector<int>& vec)
{
if (root == nullptr) return;
queue<node*> que;
que.push(root);
node* cur = nullptr;
while (!que.empty())
{
cur = que.front();
vec.push_back(cur->data);
que.pop();
if (cur->left) que.push(cur->left);
if (cur->right) que.push(cur->right);
}
}
void levelOrder1(node* root, vector<vector<int>>& vec)
{
if (root == nullptr) return;
queue<node*> que;
que.push(root);
node* curr = nullptr;
int j = 0;
while (!que.empty())
{
int len = que.size();
vector<int> svec;
for (int i = 0; i < len; ++i)
{
curr = que.front();
svec.push_back(curr->data);
que.pop();
if (curr->left) que.push(curr->left);
if (curr->right) que.push(curr->right);
}
j++;
vec.push_back(svec);
}
}
前中或者后中得其一的实现---链接
路径总和1---链接
路径总和2
对称二叉树-----左起遍历和右起遍历比较---101
相同树-----都左旗或者右起遍历比较---100
反转二叉树-----从根节点开始,左右子节点交换即可
二叉树的最近公共祖先-----236
先递进入最下层,从最下层开始往上找;
找到的条件:1,在当前节点的左右子树存在两个节点;2,当前节点就是其中一个节点,而且子树存在另一个节点