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) {
stack<TreeNode*> tree;
vector<int> ans;
if(!root) return ans;
tree.push(root);
while(tree.size()){
TreeNode* temp=tree.top();
ans.push_back(temp->val);
tree.pop();
if(temp->right)
tree.push(temp->right);
if(temp->left)
tree.push(temp->left);
}
return ans;
}