递归:
class Solution {
public:
vector<int> res;
void Get(TreeNode* p) {
if(p==NULL)
return;
Get(p->left);
res.push_back(p->val);
Get(p->right);
}
vector<int> inorderTraversal(TreeNode* root) {
Get(root);
return res;
}
};
迭代:
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> s;
while(root != nullptr || !s.empty()) {
while(root != nullptr) {
s.push(root);
root = root->left;
}
root = s.top();
s.pop();
res.push_back(root->val);
root = root->right;
}
return res;
}
};
|