Given a binary tree, return the preorder traversal of its nodes’ values.
Can you do it without recursion?
​​​http://www.lintcode.com/en/problem/binary-tree-preorder-traversal/​

1.递归

/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/

class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: Preorder in vector which contains node values.
*/
void Traversal(TreeNode *root,vector<int> &res){
if(root==NULL){
return;
}
else if(root){
res.push_back(root->val);
}
if(root->left){
Traversal(root->left,res);
}
if(root->right){
Traversal(root->right,res);
}
}

vector<int> preorderTraversal(TreeNode *root) {
// write your code here
vector<int> res;

Traversal(root,res);

return res;
}
};

2.迭代
用迭代法做深度优先搜索的技巧就是使用一个显式声明的Stack存储遍历到节点,替代递归中的进程栈。对于先序遍历,我们pop出栈顶节点,记录它的值,然后将它的左右子节点push入栈,以此类推。

/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/

class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: Preorder in vector which contains node values.
*/
vector<int> preorderTraversal(TreeNode *root) {
// write your code here

vector<int> res;

stack<TreeNode*> s;

if(root){
s.push(root);
}

while(!s.empty()){
TreeNode *node=s.top();
s.pop();
res.push_back(node->val);
if(node->right){
s.push(node->right);
}
if(node->left){
s.push(node->left);
}

}

return res;
}
};

两者的时间复杂度O(n),空间复杂度O(log n)