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> ans;
GetAns(ans, root);
return ans;
}
void GetAns(vector<int> &ans, TreeNode* root)
{
stack<TreeNode*> tree;
while(root!=NULL||!tree.empty())
{
if(root == NULL)
{
root = tree.top();
tree.pop();
root = root->right;
}
else
{
ans.push_back(root->val);
tree.push(root);
root = root->left;
}
}
}
};