链接: link
class Solution {
public:
vector<int> v;
vector<int> preorderTraversal(TreeNode* root) {
if(root==nullptr)
return v;
v.push_back(root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
return v;
}
};
链接: link
#include<iostream>
#include<string>
using std::cout;
using std::endl;
using std::string;
template<class T>
struct BTNode {
BTNode(const T& data = T())
: _left(nullptr),
_right(nullptr),
_data(data) {
}
BTNode<T>* _left;
BTNode<T>* _right;
T _data;
};
template<typename T>
struct BTree {
typedef BTNode<T> Node;
typedef Node* pNode;
static pNode CreatTree(string& s, int& ct) {
if (s[ct] == '#') {
ct++;
return nullptr;
}
pNode root = new Node(s[ct++]);
root->_left = CreatTree( s, ct);
root->_right = CreatTree( s, ct);
return root;
}//前序创造
static void PreOrder(pNode root) {
if (root == NULL) {
return;
}
PreOrder(root->_left);
cout << root->_data <<" ";
PreOrder(root->_right);
}
};
int main() {
string s;
getline(std::cin, s);
int ct = 0;
auto a=BTree<char>::CreatTree(s, ct);
BTree<char>::PreOrder(a);
return 0;
}