二叉树前序/中序/后序方法统一!!!!(注意涉及二次压栈的顺序)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*> call;//模拟递归
vector<int> res;
if(root!=nullptr) call.push(root);
while(!call.empty())
{
TreeNode* tmp = call.top();
call.pop();//取出一个结点
if(tmp!=nullptr)//中序压栈 /*只需要改变if内的顺序即可实现三种顺序调用*/
{
if(tmp->right) call.push(tmp->right);
//当前结点继续压栈(中间节点第二次遇到会之间取值,其他两个结点还需要再进行一次压栈)
call.push(tmp);
call.push(nullptr);
if(tmp->left) call.push(tmp->left);
}
else //下一个节点是第二次出现的,此时取val值加入res
{
res.push_back(call.top()->val);
call.pop();
}
}
return res;
}
};