题目链接:https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
题目如下:
思路一:递归
/**
* 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:
void pre_order(TreeNode* root,vector<int>& result){
if(root==NULL) return ;
result.push_back(root->val);
pre_order(root->left,result);
pre_order(root->right,result);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
pre_order(root,result);
return result;
}
};
思路二:迭代
/**
* 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) {
//栈可实现递归(迭代法)
//前序遍历顺序:根左右
//在栈中,右左,弹出顺序:左右
vector<int> result;
stack<TreeNode*> stk;
if(root==NULL) return result;
stk.push(root);
while(!stk.empty()){
TreeNode* node=stk.top();//根
stk.pop();
result.push_back(node->val);
if(node->right!=NULL) stk.push(node->right);//右
if(node->left!=NULL) stk.push(node->left);//左
}
return result;
}
};