- 先序:
解法一:递归:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector <int> result;
traversal(root, result);
return result;
}
private:
void traversal(TreeNode * root, vector<int> &ret){
if(root != NULL){
ret.push_back(root->val);
traversal(root->left, ret);
traversal(root->right, ret);
}
}
};
解法二:Divide and Conquer
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
if(root != NULL){
vector<int> left = preorderTraversal(root->left);
vector<int> right = preorderTraversal(root->right);
result.push_back(root->val);
result.insert(result.end(), left.begin(), left.end());
result.insert(result.end(), right.begin(), right.end());
}
return result;
}
};
解法三:迭代:
借助栈,先压入右节点,再压入左节点。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> s;
if(root == NULL) return result;
s.push(root);
while(!s.empty()){
TreeNode * tmp = s.top();
s.pop();
result.push_back(tmp->val);
if(tmp->right){
s.push(tmp->right);
}
if(tmp->left){
s.push(tmp->left);
}
}
return result;
}
};