【力扣 002】144. 二叉树的前序遍历
144. 二叉树的前序遍历
遍历方法:
- 访问根结点;
- 先序遍历其左子树;
- 先序遍历其右子树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root)
{
if(!root) return {};
stack<TreeNode*> st;
vector<int> res;
st.push(root);
while(!st.empty())
{
auto p = st.top();
st.pop();
res.push_back(p->val);
if(p->right) st.push(p->right);
if(p->left) st.push(p->left);
}
return res;
}
};