简单遍历
class Solution {
public:
void qian(TreeNode* root,vector<int> &v)
{
if(!root)return ;
v.push_back(root->val);
qian(root->left,v);
qian(root->right,v);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> v;
qian(root,v);
return v;
}
};
递归版本只以前序遍历为例,下面所述遍历均为迭代算法
前序遍历
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> v;
stack<TreeNode*> s;
while(!s.empty()||root)
{
while(root)
{
v.push_back(root->val);
s.push(root);
root=root->left;
}
root=s.top();s.pop();
root=root->right;
}
return v;
}
};
中序遍历
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ans;
stack<TreeNode*> s;
while(!s.empty()||root)
{
while(root)
{
s.push(root);
root=root->left;
}
root=s.top();s.pop();
ans.push_back(root->val);
root=root->right;
}
return ans;
}
};
后序遍历
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> v;
stack<TreeNode*> s;
TreeNode* t=nullptr;
while(root||!s.empty())
{
while(root)
{
s.push(root);
root=root->left;
}
root=s.top();s.pop();
if(!root->right||root->right==t)
{
v.push_back(root->val);
t=root;
root=nullptr;
}
else
{
s.push(root);
root=root->right;
}
}
return v;
}
};
|