//144.Binary Tree preorder
struct Command{
TreeNode* node;
string s;
Command(string s,TreeNode* node):s(s),node(node){}
};
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(root ==NULL){
return res;
}
stack<Command> stack;
stack.push(Command("go",root));
while(!stack.empty()){
Command com=stack.top();
stack.pop();
if(com.s=="print"){
//deal with recurision end condition
res.push_back(com.node->val);
} else{
assert(com.s=="go");
// not same order compared recurison
if(com.node->right){
stack.push(Command("go",com.node->right));
}
if(com.node->left){
stack.push(Command("go",com.node->left));
}
stack.push(Command("print",com.node));
}
}
return res;
}
};
Binary Tree Preorder Traversal
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
相关阅读更多精彩内容
- 递归版本 1#LeetCode 144. Binary Tree Preorder Traversal Given...
- My code: My test result: 考先序遍历的,没什么好说的。 非递归写法: **总结: pre ...