递归遍历
//前序遍历
class Solution {
public:
//前
void traversal(TreeNode* root,vector<int>& nums)
{
if(root==nullptr)
{
return;
}
nums.push_back(root->val);
traversal(root->left,nums);
traversal(root->right,nums);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> nums;
traversal(root,nums);
return nums;
}
};
//中序遍历
class Solution {
public:
void traversal(TreeNode* root,vector<int>& nums)
{
if(root==nullptr)
{
return;
}
traversal(root->left,nums);
nums.push_back(root->val);
traversal(root->right,nums);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> nums;
traversal(root,nums);
return nums;
}
};
//后序遍历
class Solution {
public:
//后
void traversal(TreeNode* root,vector<int>& nums)
{
if(root==nullptr)
{
return;
}
traversal(root->left,nums);
traversal(root->right,nums);
nums.push_back(root->val);
}
vector<int> postorderTraversal(TreeNode* root) {
vector<int> nums;
traversal(root,nums);
return nums;
}
};
迭代遍历
//前序遍历
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> result;
if(root == nullptr)
{
return result;
}
st.push(root);
while(!st.empty())
{
TreeNode* node = st.top();
st.pop();
result.push_back(node->val);
if(node->right) st.push(node->right);
if(node->left) st.push(node->left);
}
return result;
}
};
//中序遍历
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> result;
TreeNode* cur = root;
while(cur!=nullptr || !st.empty())
{
if(cur!=nullptr)
{
st.push(cur);
cur =cur->left;
}
else{
cur =st.top();
st.pop();
result.push_back(cur->val);
cur =cur->right; }
}
return result;
}
};
//后序遍历
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> result;
if(root == nullptr)
{
return result;
}
st.push(root);
while(!st.empty())
{
TreeNode* node = st.top();
st.pop();
result.push_back(node->val);
if(node->left) st.push(node->left);
if(node->right) st.push(node->right);
}
reverse(result.begin(),result.end());
return result;
}
}
102 层序遍历
class Solution {
public:
void order(TreeNode* root,vector<vector<int>>& result,int depth)
{
if(root == nullptr)
{
return ;
}
if(result.size()==depth) result.push_back(vector<int>());
result[depth].push_back(root->val);
order(root->left,result,depth+1);
order(root->right,result,depth+1);
}
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> result;
order(root, result, 0);
return result;
}
};