Given a binary tree, return the preordertraversal 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?
方法一:非递归实现:[cpp] view plain copyclass Solution
{
public:
vector<int> preorderTraversal(TreeNode* root)
{
vector<int> res;
if (!root)
{
return res;
}
stack<TreeNode*> st;
st.push(root);
while (st.size())
{
TreeNode* tmp = st.top();
st.pop();
res.push_back(tmp->val);
if (tmp->right)
{
st.push(tmp->right);
}
if (tmp->left)
{
st.push(tmp->left);
}
}
return res;
}
};
class Solution
{
public:
vector<int> preorderTraversal(TreeNode* root)
{
vector<int> ans;
LRD(ans, root);
return ans;
}
void LRD(vector<int>&ans, TreeNode* root)
{
if (root==NULL)
{
return;
}
ans.push_back(root->val);
LRD(ans, root->left);
LRD(ans, root->right);
}
};