二叉树深度搜索-前中后三序遍历-递归法
分析:注意递归的三个要素
#include "_myPrint.cpp"
#include "_TreeNode.cpp"
using namespace std;
class Solution{
public:
void travel(TreeNode* cur, vector<int>& vec){
if (cur == NULL) return;
vec.push_back(cur -> val);
travel(cur -> left, vec);
travel(cur -> right, vec);
}
vector<int> preorder(TreeNode* root){
vector<int> res;
travel(root, res);
return res;
}
};
int main(){
Solution s;
TreeNode* root = new TreeNode(8);
TreeNode* l = new TreeNode(7);
TreeNode* r = new TreeNode(6);
root->left = l;
root->right = r;
vector<int> res = s.preorder(root);
printCollection p;
p.printVector(res);
}
struct TreeNode{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
|