day10打卡

ikun1111發表於2024-08-30

遞迴遍歷

前序遍歷
/**

  • 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 preorderTraversal(TreeNode
    root)
    {
    vector ret;
    stack<TreeNode *> st;
    if(root)
    {
    st.push(root);
    }
    while(!st.empty())
    {
    TreeNode *cur = st.top();
    if(cur)
    {
    st.pop();
    if(cur->right)
    {
    st.push(cur->right);
    }
    if(cur->left)
    {
    st.push(cur->left);
    }
    st.push(cur);
    st.push(nullptr);
    }
    else
    {
    st.pop();
    cur = st.top();
    st.pop();
    ret.push_back(cur->val);
    }
    }
    return ret;
    }
    };

後序遍歷

class Solution
{
public:
void traversal(TreeNode root, vector &vec)
{
if(root == nullptr)
{
return;
}
traversal(root->left, vec);
traversal(root->right, vec);
vec.push_back(root->val);
}
vector postorderTraversal(TreeNode
root)
{
vector vec;
traversal(root, vec);
return vec;
}
};

中序遍歷

class Solution
{
public:
vector inorderTraversal(TreeNode *root)
{
vector ret;
if(root == nullptr)
{
return ret;
}
stack<TreeNode *> st;
TreeNode *cur = root;
while(!st.empty() || cur != NULL)
{
if(cur != NULL)
{
st.push(cur);
cur = cur->left;
}
else
{
cur = st.top();
ret.push_back(cur->val);
st.pop();
cur = cur->right;
}
}
return ret;
}
};

層序遍歷

class Solution
{
public:
vector<vector> levelOrder(TreeNode* root)
{
queue<TreeNode *> que;
vector<vector> ret;
if(root)
{
que.push(root);
ret.push_back(vector{root->val});
}
vector vec;
while(!que.empty())
{
vec.clear();
int size = que.size();
for(int i = 0; i < size; ++i)
{
TreeNode *node = que.front();
que.pop();
if(node->left)
{
que.push(node->left);
vec.push_back(node->left->val);
}
if(node->right)
{
que.push(node->right);
vec.push_back(node->right->val);
}
}
if(!vec.empty())
{
ret.push_back(vec);
}
}
return ret;
}
};