前序遍历(递归):
vector<int> preorderTraversal(TreeNode* root) {
vector<int> arr;
dfs(root,arr);
return arr;
}
void dfs(TreeNode *temp, vector<int>&temp1)
{ if(temp==NULL)
return ;
temp1.push_back(temp->val);
dfs(temp->left,temp1);
dfs(temp->right,temp1);
}
中序遍历(递归):
vector<int> inorderTraversal(TreeNode* root) {
vector<int> arr;
find(root,arr);
return arr;
}
void find(TreeNode *temp,vector<int> &temp_a)
{
if(temp==NULL)
{
return ;
}
// 递归查找最左,直到左为空,退出当前递归
find(temp->left,temp_a);
// 加入根
temp_a.push_back(temp->val);
// 查找右端点
find(temp->right,temp_a);
}
后序遍历(递归):
vector<int> postorderTraversal(TreeNode* root) {
vector<int> arr;
find(root,arr);
return arr;
}
void find(TreeNode *temp,vector<int>& arr)
{
if(temp==NULL) return;
find(temp->left,arr);
find(temp->right,arr);
arr.push_back(temp->val);
}