题目:
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]
.
Note: Recursive solution is trivial, could you do it iteratively?
思路:
常规的递归调用PreOrder Traversal
代码:
递归版本
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> v;
vector<int> preorderTraversal(TreeNode *root) {
preorder(root);
return v;
}
void preorder(TreeNode *root)
{
if(root !=NULL)
{
v.push_back(root->val);
preorder(root->left);
preorder(root->right);
}
}
};
非递归版本
/**
* Definition for binary tree
* 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> result;
stack<TreeNode*> node;
if(root != NULL){
node.push(root);
}
while(!node.empty()){
TreeNode* p = node.top();
node.pop();
result.push_back(p->val);
if(p->right != NULL){
node.push(p->right);
}
if(p->left != NULL){
node.push(p->left);
}
}
return result;
}
};