一、题目要求
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].
二、代码实现
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> st;
if(root==NULL)
return result;
//
st.push(root);
TreeNode* tmp;
while(!st.empty())
{
tmp=st.top();
st.pop();
result.push_back(tmp->val);
if(tmp->right!=NULL)
{
st.push(tmp->right);
}
if(tmp->left!=NULL)
{
st.push(tmp->left);
}
}
return result;
}