给你二叉树的根节点 root
,返回它节点值的 前序 遍历。
解法一:递归
class Solution {
public:
vector<int>res;
vector<int> preorderTraversal(TreeNode* root) {
dfs(root);
return res;
}
void dfs(TreeNode* root){
if(root){
res.push_back(root->val);
}
else return;
if(root->left)dfs(root->left);
if(root->right)dfs(root->right);
}
};
解法二:利用栈进行迭代(右结点先入栈,以便下一次操作的是左结点)
class Solution {
public:
vector<int>res;
vector<int> preorderTraversal(TreeNode* root) {
if(!root)return res;
stack<TreeNode*>st;
st.push(root);
while(st.size()){
TreeNode* rt = st.top();
res.push_back(rt->val);
st.pop();
if(rt->right)st.push(rt->right);
if(rt->left)st.push(rt->left);
}
return res;
}
};