二叉树的前序遍历即先读取根节点,再读取左节点然后是右节点。具体方法可以通过递归和非递归来实现。非递归即为栈的调用,递归函数的入口就相当于入栈,递归的返回就是出栈。
1,非递归
对于每一颗子树,先读根节点,然后遍历左子树,再遍历右子树。
void dfs(TreeNode * root,vector<int> &res)
{
if(root==NULL )
return;
res.push_back (root->val );
dfs(root->left,res );
dfs(root->right ,res);
}
vector<int> preorder(TreeNode *root)
{
vector<int> res;
if(root==NULL )
return res;
dfs(root,res);
return res;
}
2.非递归
非递归即为通过栈的调用来实现与递归相同的功能。
和中序遍历相同的思路,一直遍历左子树,直到子节点为止,然后再遍历右节点。区别在于左节点入栈的时候先读取再入栈。
vector<int> preorder(TreeNode *root)
{
vector<int> res;
stack<TreeNode *> temp;
while(root!=NULL ||!temp.empty ())
{
if(root!=NULL )
{
res.push_back (root->val );
temp.push (root);
root=root->left ;
}
else
{
root=temp.top();
temp.pop();
root=root->right ;
}
}
return res;
}