二叉树的前序遍历(非递归)
程序员文章站
2022-05-20 21:34:40
...
题目描述
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree{1,#,2,3},
1 \ 2 / 3
return[1,2,3].
Note: Recursive solution is trivial, could you do it iteratively?
Solution 1(非递归)
/**
* Definition for binary tree
* 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;
if(root==nullptr) return res;
stack<TreeNode*>q;
q.push(root);
while(!q.empty())
{
TreeNode *front=q.top();
q.pop();
res.push_back(front->val);
if(front->right!=nullptr)
q.push(front->right);
if(front->left!=nullptr)
q.push(front->left);
}
return res;
}
};
Solution 2(递归写法)
/**
* Definition for binary tree
* 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;
if(root==nullptr) return res;
preOrder(root,res);
return res;
}
private:
void preOrder(TreeNode *ptr,vector<int>&v)
{
if(ptr!=nullptr)
{
v.push_back(ptr->val);
preOrder(ptr->left,v);
preOrder(ptr->right,v);
}
}
};