题目描述【Leetcode】
Given a binary tree, return the preorder traversal of its nodes’ values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,2,3].Note: Recursive solution is trivial, could you do it iteratively?
用迭代法做先序遍历
/**
* 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>re;
if(!root) return re;
stack<TreeNode*>nodes;
nodes.push(root);
while(!nodes.empty()){
TreeNode* temp = nodes.top();
re.push_back(temp->val);
nodes.pop();
if(temp->right) nodes.push(temp->right);
if(temp->left) nodes.push(temp->left);
}
return re;
}
};