地址:http://oj.leetcode.com/problems/binary-tree-preorder-traversal/
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 binary tree
* 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;
vector<int>vec;
TreeNode* p = root;
while(p)
{
while(p)
{
st.push(p);
vec.push_back(p->val);
p = p->left;
}
while(!st.empty() && !(st.top()->right))
{
st.pop();
}
if(!st.empty())
{
p = st.top()->right;
st.pop();
}
}
return vec;
}
};