结点定义
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
1、二叉树的前序遍历(递归+非递归)
void PrevOrder(TreeNode* root)
{
if (root == nullptr)
return;
cout << root->val << " ";
PrevOrder(root->left);
PrevOrder(root->right);
}
void PrevOrderNR(TreeNode* root)
{
stack<TreeNode*> st;
st.push(root);
while (!st.empty())
{
TreeNode* cur = st.top();
st.pop();
cout << cur->val << " ";
if (cur->right != nullptr)
st.push(cur->right);
if (cur->left != nullptr)
st.push(cur->left);
}
}
void PrevOrderNR(TreeNode* root)
{
stack<TreeNode*> st;
TreeNode* cur = root;
while (cur || !st.empty())
{
while (cur)
{
cout << cur->val << " ";
st.push(cur);
cur = cur->left;
}
cur = st.top()->right;
st.pop();
}
}
2、二叉树的序遍中历(递归+非递归)
void InOrder(TreeNode* root)
{
if (root == nullptr)
return;
InOrder(root->left);
cout << root->val << " ";
InOrder(root->right);
}
void InOrderNR(TreeNode* root)
{
stack<TreeNode*> st;
TreeNode* cur = root;
while (cur || !st.empty())
{
while (cur)
{
st.push(cur);
cur = cur->left;
}
cur = st.top()->right;
cout << st.top()->val << " ";
st.pop();
}
}
3、二叉树的序遍后历(递归+非递归)
void PostOrder(TreeNode* root)
{
if (root == nullptr)
return;
PostOrder(root->left);
PostOrder(root->right);
cout << root->val << " ";
}
void PostOrderNR(TreeNode* root)
{
stack<TreeNode*> st;
TreeNode* cur = root;
TreeNode* prev = nullptr;
while (cur || !st.empty())
{
while (cur)
{
st.push(cur);
cur = cur->left;
}
TreeNode* top = st.top();
if (top->right == nullptr || top->right == prev)
{
cout << top->val << " ";
prev = top;
st.pop();
}
else
{
cur = top->right;
}
}
}
4、二叉树的层序遍历
void levelOrder(TreeNode* root)
{
if (root == nullptr)
return;
queue<TreeNode*> q;
q.push(root);
while (!q.empty())
{
TreeNode* cur = q.front();
q.pop();
cout << cur->val << " ";
if (cur->left != nullptr)
q.push(cur->left);
if (cur->right != nullptr)
q.push(cur->right);
}
}