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]
.
/**
* 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>v;
v.clear();
stack<TreeNode*>s;
TreeNode* x;
s.push(root);
if(!root) return v;
while(!s.empty()){
x=s.top();
v.push_back(x->val);
s.pop();
if(x->right) s.push(x->right);
if(x->left) s.push(x->left);
}
return v;
}
};
class Solution { //先序遍历 递归
public:
vector<int>v;
vector<int> preorderTraversal(TreeNode* root) {
v.clear();
if(!root) return v;
pre(root);
return v;
}
void pre(TreeNode* p){
if(!p) return;
v.push_back(p->val);
pre(p->left);
pre(p->right);
}
};