结合栈完成非递归的前序遍历
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
if(root==nullptr)
return result;
stack<TreeNode*> _stack;
_stack.push(root);
while(!_stack.empty()){
TreeNode* tmp=_stack.top();
_stack.pop();
result.push_back(tmp->val);
if(tmp->right)
_stack.push(tmp->right);
if(tmp->left)
_stack.push(tmp->left);
}
return result;
}
};
执行用时 :8 ms, 在所有 C++ 提交中击败了42.91%的用户
内存消耗 :8.9 MB, 在所有 C++ 提交中击败了97.22%的用户
还是很慢的。
另一种写法,先存根节点,再把所有的左孩子存入,并存储左孩子结点的值,等结点左孩子为空,再访问存储右结点。
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
if(root==nullptr)
return result;
stack<TreeNode*> S;
TreeNode* cur=root;
while(cur!=nullptr or !S.empty()){
if(cur!=nullptr){
result.push_back(cur->val);
S.push(cur);
cur=cur->left;
}else{
cur=S.top();
S.pop();
cur=cur->right;
}
}
return result;
}
};
执行用时 :4 ms, 在所有 C++ 提交中击败了84.99%的用户
内存消耗 :9.1 MB, 在所有 C++ 提交中击败了66.80%的用户