先序遍历的非递归办法,还是要用到一个stack
class Solution { public: vector<int> preorderTraversal(TreeNode* root) { vector<int> ret; if(!root) return ret; stack<TreeNode*> stk; stk.push(root); //ahd(root) //a(stk) //a(ret) while(stk.size()>0){ TreeNode* cur=stk.top(); stk.pop(); //a(cur) //lk("root", cur) ret.push_back(cur->val); //dsp if(cur->right) stk.push(cur->right); if(cur->left) stk.push(cur->left); //dsp } return ret; } };
程序运行动态演示:http://simpledsp.com/FS/Html/lc144.html
原文地址:https://www.cnblogs.com/leetcoder/p/11337343.html
时间: 2024-11-10 13:45:55