1.前序遍历 力扣相关题目
/**
* Definition for a binary tree node.
* 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) {}
* };
*/
class Solution {
public:
vector<int> ans;
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*> stk;
TreeNode* p=root;
while(stk.size() || p)
{
if(p)
{
stk.push(p);
ans.push_back(p->val);
p=p->left;
}
else{
TreeNode* t=stk.top();
stk.pop();
p=t->right;
}
}
return ans;
}
};
可以换成数组node *stk[101];int tt=-1;
void pre(node *root)
{
// stack<node*> stk;
node *stk[101];
int tt=-1;
node *p=root;
//stk.size()
while(tt>-1 || p)
{
if(p)
{
stk[++tt]=p;
cout<<p->val<<" ";
p=p->left;
}
else{
node *t=stk[tt--];
p=t->right;
}
}
}
2.中序遍历 力扣相关题目
从根节点开始,先将根节点压入栈,然后再将其所有左子结点压入栈,然后取出栈顶结点,保存结点值,再将其指针移到右子节点上,若存在右子结点,则在下次循环中又可以将其所有左子结点压入栈中,这样就保证了访问顺序为左-根-右。
/**
* 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> ans;
vector<int> inorderTraversal(TreeNode* root) {
if(!root) return ans;
stack<TreeNode*> stk;
TreeNode *p=root;
while(stk.size() || p)
{
if(p)
{
stk.push(p);
p=p->left;
}
else{
TreeNode *t=stk.top();
stk.pop();
ans.push_back(t->val);
p=t->right;
}
}
return ans;
}
};
3.后序遍历(与前序比较着看) 力扣相关题目
先将先序遍历的根-左-右变成根-右-左,再翻转变为左-右-根,翻转方式为改变结构ans的加入顺序,每次从头部插入元素,然后把更新辅助结点p的左右顺序换一下。
/**
* Definition for a binary tree node.
* 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) {}
* };
*/
*
class Solution {
public:
vector<int> ans;
vector<int> postorderTraversal(TreeNode* root) {
if(!root) return ans;
stack<TreeNode*> stk;
TreeNode *p=root;
while(stk.size() || p)
{
if(p)
{
stk.push(p);
ans.insert(ans.begin(),p->val);
p=p->right;
}
else{
TreeNode *t=stk.top();
stk.pop();
p=t->left;
}
}
return ans;
}
};*