1. 前序遍历
class Solution {
public:
stack<TreeNode*> stack;
vector<int> res;
vector<int> preorderTraversal(TreeNode* root) {
TreeNode* cur = root;
while (!stack.empty()|| cur) {
while (cur) {
res.push_back(cur->val);
stack.push(cur);
cur = cur->left;
}
cur = stack.top()
stack.pop();
cur = cur->right;
}
return res;
}
};
2. 中序遍历
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode* > stack;
TreeNode* cur = root;
vector<int> res;
while(cur || !stack.empty()){
while(cur){
stack.push(cur);
cur = cur->left;
}
cur = stack.top();
stack.pop();
res.push_back(cur->val);
cur = cur ->right;
}
return res;
}
};
前序遍历和中序遍历的非递归算法,差别就是
res.push_back(cur->val)
,语句的位置;
网友评论