刷leetcode,评论里面看到的,分享一下。
这种写法的时间性能并不是最优解,但是它统一了前中后序遍历的迭代写法(只用移动左、右、自身结点进栈的顺序),很方便记忆!
前序遍历:
vector<int> preorderTraversal(TreeNode* root) {
if(!root) return {};
vector<int> result;
stack<TreeNode*> stk;
stk.push(root);
while(!stk.empty()){
TreeNode* node = stk.top();
stk.pop();
if(node){
if(node -> right){
stk.push(node -> right);
}
if(node -> left){
stk.push(node -> left);
}
stk.push(node);
stk.push(nullptr);
}else{
result.push_back(stk.top()->val);
stk.pop();
}
}
return result;
}
中序遍历:
vector<int> inorderTraversal(TreeNode* root) {
if(!root) return {};
vector<int> result;
stack<TreeNode*> stk;
stk.push(root);
while(!stk.empty()){
TreeNode* node = stk.top();
stk.pop();
if(node){
if(node -> right){
stk.push(node -> right);
}
stk.push(node);
stk.push(nullptr);
if(node -> left){
stk.push(node -> left);
}
}else{
result.push_back(stk.top()->val);
stk.pop();
}
}
return result;
}
后序遍历:
vector<int> postorderTraversal(TreeNode* root) {
if(!root) return {};
vector<int> result;
stack<TreeNode*> stk;
stk.push(root);
while(!stk.empty()){
TreeNode* node = stk.top();
stk.pop();
if(node){
stk.push(node);
stk.push(nullptr);
if(node -> right){
stk.push(node -> right);
}
if(node -> left){
stk.push(node -> left);
}
}else{
result.push_back(stk.top()->val);
stk.pop();
}
}
return result;
}
|