struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
using node = TreeNode;
/*先序遍历1
根-左-右,修改入栈顺序可以变成 根-右-左,然后将结果逆序,就是后序遍历了。
*/
//先序遍历的第一种写法。
void preOrderIter(node *root)
{
if (root == NULL) return;
stack<node *> s;
s.push(root);
while (!s.empty())
{
node *nd = s.top();
cout << nd->val << " ";
s.pop();
if (nd->right != NULL) s.push(nd->right);
if (nd->left != NULL) s.push(nd->left);
}
}
//先序遍历方法二
//先序2和中序一模一样,所以记住这一个就行了,如果你基础薄弱,那么死记这个,因为它再稍加修改,就可以变成后序遍历。
void preOrderIter2(node *root)
{
stack<node *> s;
while (root != NULL || !s.empty()) {
if (root != NULL)
{
cout << root->val << " "; //访问结点并入栈
s.push(root);
root = root->left; //访问左子树
}
else
{//表示左树访问完毕
root= s.top(); //回溯至父亲结点
s.pop();//父节点出栈
root = root->right; //访问右子树
}
}
}
/*
中序遍历。和先序2只有访问顺序不一样。
*/
void inOrderIter(node *root)
{
stack<node *> s;
while (root != NULL || !s.empty()) {
if (root != NULL) {
s.push(root);
root = root->left;
}
else {
root = s.top();
cout << root->val << " "; //访问完左子树后才访问根结点
s.pop();
root = root->right; //访问右子树
}
}
}
/*后序遍历1,两个栈。后序遍历还可以通过修改先序2来实现
*/
void postOrderIter(node *root)//我们需要把先序遍历反过来,left和right互换,这和我们第一个先序遍历很像
{
if (!root) return;
stack<node*> s;
stack<node*>output;
s.push(root);//先压到第一个栈
while (!s.empty())
{
node *curr = s.top();
output.push(curr);//当前节点压到输出栈
s.pop();
if (curr->left) s.push(curr->left);
if (curr->right) s.push(curr->right);
}
while (!output.empty()) {//这是依次出栈访问
cout << output.top()->val << " ";
output.pop();
}
}
/*
后序遍历2。这是从先序遍历修改而来,最后需要reverse 容器,实际上就是用它代替栈,
这样,我们就只需要记忆先序方法2,灵活运用之即可。
*/
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> s;
vector<int> result;
while (root || !s.empty())
{
if (root)
{
result.push_back(root->val);//访问结点并入栈
s.push(root);
root = root->right; //访问左子树
}
else
{//表示右树访问完毕
root = s.top(); //回溯至父亲结点
s.pop();//父节点出栈
root = root->left; //访问右子树
}
}
reverse(result.begin(), result.end());
return result;
}
/*
层次遍历。这个写法虽然用了两个队列,但是符合真正的层的概念。如果希望剩下一个队列,你需要记录队列长度。
*/
void levelOrderIter(node* root)
{
if (!root) return;
queue<node *> currentLevel, nextLevel;
currentLevel.push(root);
while (!currentLevel.empty()) {
node *currNode = currentLevel.front();
currentLevel.pop();
if (currNode) {
cout << currNode->val << " ";
nextLevel.push(currNode->left);
nextLevel.push(currNode->right);
}
if (currentLevel.empty()) {
cout << endl;
swap(currentLevel, nextLevel);
}
}
}