建议先阅读二叉树的中序遍历
前序遍历顺序为根 -> 左 -> 右
,所以运用递归算法时,先将该点放入遍历数组,再递归遍历左子树和右子树
递归算法
/**
* 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> res;
vector<int> preorderTraversal(TreeNode* root) {
dfs(root);
return res;
}
void dfs(TreeNode* p)
{
if (!p) return;
res.push_back(p -> val);
dfs(p -> left);
dfs(p -> right);
}
};
迭代算法
当前遍历结点即为根
,所以在迭代算法中,先将该点放入遍历数组,然后将左子树链递
到最低层,然后出栈,放入右子树。
/**
* 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> res;
stack<TreeNode*> st;
auto p = root;
while (p || !st.empty())
{
while (p)
{
res.push_back(p -> val);
st.push(p);
p = p -> left;
}
p = st.top();
st.pop();
p = p-> right;
}
return res;
}
};