- Binary Tree Preorder Traversal
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].
1、递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
vector<int >answer;
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
answer.clear();
mypreorder(root);
return answer;
}
void mypreorder(TreeNode* root){
if(root==NULL)
return ;
else{
answer.push_back(root->val);
if(root->left==NULL&root->right==NULL)
return;
if(root->left!=NULL)
mypreorder(root->left);
if(root->right!=NULL)
mypreorder(root->right);
}
}
};
2、非递归
/**
* 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> preorderTraversal(TreeNode* root) {
vector<int >answer;
answer.clear();
stack<TreeNode*> stack_pre;
if(root==NULL)
return answer;
else{
stack_pre.push(root);
while(!stack_pre.empty()){
TreeNode* top_node=stack_pre.top();
answer.push_back(top_node->val);
stack_pre.pop();
if(top_node->right!=NULL)
stack_pre.push(top_node->right);
if(top_node->left!=NULL)
stack_pre.push(top_node->left);
}
}
return answer;
}
};