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?
递归代码如下:
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(root==NULL) return res;
return pre(root,res);
}
vector<int> pre(TreeNode* root,vector<int>& res)
{
if(root)
{
res.push_back(root->val);
pre(root->left,res);
pre(root->right,res);
}
return res;
}
};
迭代代码如下:
前序遍历,相当于深度搜索,可用堆栈实现,先进后出,先右后左。参考http://blog.csdn.net/sinat_24520925/article/details/45081749
代码如下:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(root==NULL) return res;
stack<TreeNode*> st;
st.push(root);
while(!st.empty())
{
TreeNode *p=st.top();
st.pop();
res.push_back(p->val);
if(p->right) st.push(p->right);
if(p->left) st.push(p->left);
}
return res;
}