Leetcode144
1.问题描述
2.解决方案
解法一:递归
没什么好说的,vector< int >& ans,记得加引用!
class Solution {
public:
void pre(TreeNode* root,vector<int>& ans){
if(root== nullptr) return;
ans.push_back(root->val);
pre(root->left,ans);
pre(root->right,ans);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> ans;
pre(root,ans);
return ans;
}
};
解法二:迭代
其实也比较简单,过程图已经画的很清楚了,总体上就分两步
1.取栈顶
2.入栈右儿子,左儿子(先右儿子后左儿子)
class Solution1 {
public:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*> s;
vector<int> ans;
if(root== nullptr) return ans;
s.push(root);
while(s.empty()== false){
//1.取栈顶
TreeNode* cur=s.top();
ans.push_back(cur->val);
s.pop();
//2.入栈右左儿子
if(cur->right!= nullptr) s.push(cur->right);
if(cur->left!= nullptr) s.push(cur->left);
}
return ans;
}
};