/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(!root) return res;
stack<TreeNode*> st;
TreeNode* cur = root;
while(cur || !st.empty()){
while(cur){
st.push(cur);
res.push_back(cur->val);
cur = cur->left;
}
cur = st.top();
st.pop();
cur=cur->right;
}
return res;
}
};
144. 二叉树的前序遍历/C++
最新推荐文章于 2024-07-28 17:42:24 发布