非递归堆栈实现
class Solution {
public:
vector<int> result;
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*> s;
while(root||!s.empty()){
if(root){
result.push_back(root->val);
s.push(root);
root=root->left;
}
else{
root=s.top();
s.pop();
root=root->right;
}
}
return result;
}
};
递归
class Solution {
public:
vector<int> result;
vector<int> preorderTraversal(TreeNode* root) {
if(root){
result.push_back(root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
return result;
}
};
|