题目描述:
给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
递归的写法没什么可说的,基本功
/**
* 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:
void preorder(TreeNode* root,vector<int> &res){
if(root==NULL)
return ;
res.push_back(root->val);
preorder(root->left,res);
preorder(root->right,res);
}
vector<int> preorderTraversal(TreeNode* root) {
if(root==NULL)
return {};
vector<int> res;
preorder(root,res);
return res;
}
};
迭代算法:使用stack来实现迭代算法,完成前序遍历,右子树先入栈,然后再左子树入栈
/**
* 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) {
if(root==NULL)
return {};
vector<int> res;
stack<TreeNode*> s;
s.push(root);
while(!s.empty()){
TreeNode* now=s.top();
s.pop();
if(now->right)
s.push(now->right);
if(now->left)
s.push(now->left);
res.push_back(now->val);
}
return res;
}
};