- 题目描述
给定一个二叉树,返回它的 前序 遍历。
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
-
思路
方法一:递归
方法二:非递归,利用栈,输入根-右-左,输出根-左-右 -
c++实现
方法一:
class Solution {
public:
void preorder(TreeNode *root,vector<int> &vec)
{
if(root!=NULL)
{
vec.push_back(root->val);
preorder(root->left,vec);
preorder(root->right,vec);
}
}
vector<int> preorderTraversal(TreeNode *root) {
vector<int> res;
preorder(root,res);
return res;
}
};
方法二:
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
vector<int> res;
if(root==NULL)
return res;
TreeNode *cur=root;
stack<TreeNode*> s;
s.push(root);
while(!s.empty())
{
cur=s.top();
res.push_back(cur->val);
s.pop();
if(cur->right!=NULL)
s.push(cur->right);
if(cur->left!=NULL)
s.push(cur->left);
}
return res;
}
};