这道题是LeetCode里的第144道题。
题目要求:
给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3 输出: [1,2,3]进阶: 递归算法很简单,你可以通过迭代算法完成吗?
解题代码:
/**
* 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) {
stack<TreeNode*>st;//保存上一层的节点
TreeNode *pt;//指针
vector<int>res;//结果
if(root==NULL)
return res;
pt=root;
while(pt!=NULL||st.size()!=0){
while(pt!=NULL){//遍历完所有的左子树,同时入栈保存顺序
st.push(pt);
res.push_back(pt->val);//储存结果
pt=pt->left;
}
pt=st.top();//返回上一层
st.pop();
pt=pt->right;//右子树
}
return res;
}
};