二叉树前序遍历几种写法
递归
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> s;
if(root == NULL){
return s;
}
preorderTraversal(root, s);
return s;
}
void preorderTraversal(TreeNode *root,vector<int> &result){
if(root == NULL){
return;
}
result.push_back(root->val);
preorderTraversal(root->left,result);
preorderTraversal(root->right,result);
}
};
非递归