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?
vector<int> preorderTraversal(TreeNode *root)
{
vector<int> result;
if(root == NULL)
return result;
stack<TreeNode*> st;
st.push(root);
TreeNode* temp = NULL;
while(!st.empty())
{
temp = st.top();
st.pop();
result.push_back(temp->val);
if(temp->right != NULL)
st.push(temp->right);
if(temp->left != NULL)
st.push(temp->left);
}
return result;
}
用桟分别保存当前节点的右子女与左子女即可
已AC 12ms