https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
思路一:根左右,遞歸版隨便寫。
/**
* 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> ans;
void preorder(TreeNode *root){
ans.push_back(root->val);
if(root->left)
preorder(root->left);
if(root->right)
preorder(root->right);
}
vector<int> preorderTraversal(TreeNode* root) {
if(root==NULL)
return ans;
preorder(root);
return ans;
}
};
思路二:非遞歸版,搞一個棧,因爲棧是後進先出的,所以每次先把棧頂節點的右兒子壓進去,再把左兒子壓進去即可。
/**
* 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> ans;
vector<int> preorderTraversal(TreeNode* root) {
if(root==NULL)
return ans;
stack<TreeNode*> stk;
stk.push(root);
TreeNode *cur;
while(!stk.empty()){
cur=stk.top();
stk.pop();
ans.push_back(cur->val);
if(cur->right)
stk.push(cur->right);
if(cur->left)
stk.push(cur->left);
}
return ans;
}
};