题目
代码实现
递归版
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: A Tree
* @return: Preorder in ArrayList which contains node values.
*/
vector<int> ans;
void dfs(TreeNode* t){
if(!t) return ;
ans.push_back(t->val);
dfs(t->left);
dfs(t->right);
}
vector<int> preorderTraversal(TreeNode * root) {
// write your code here
dfs(root);
return ans;
}
};
非递归版
思路
当想尽办法也无法“凭空”地不用递归解决问题时,可以考虑借助“外力”——数据结构;
本题借用的是——栈;
为什么用栈不用队列呢?因为队列的特点是 先进先出,而栈的特点是后进先出;且根据题目要求我们要求的是前序遍历,所以说结合一定的思考【我表达能力差。。。】,用栈会是明智的选择。
先考虑右子树,若不为空则压栈;
再考虑左子树,若不为空则压栈。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: A Tree
* @return: Preorder in ArrayList which contains node values.
*/
vector<int> ans;
vector<int> preorderTraversal(TreeNode * root) {
// write your code here
stack<TreeNode*> stk;
TreeNode* t;
if(!root)
return ans;
stk.push(root);
while(!stk.empty()){
t = stk.top();
stk.pop();
ans.push_back(t->val);
if(t->right) stk.push(t->right);
if(t->left) stk.push(t->left);
}
return ans;
}
};