leetcode[144]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].

Note: Recursive solution is trivial, could you do it iteratively?

/**
 * 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> res;
        if(root==NULL)return res;
        stack<TreeNode *> sta;
        sta.push(root);
        while(!sta.empty())
        {
            TreeNode *tmp=sta.top();
            sta.pop();
            res.push_back(tmp->val);
            if(tmp->right)sta.push(tmp->right);
            if(tmp->left)sta.push(tmp->left);
        }
        return res;
    }
/**
void preorder(vector<int> &res, TreeNode * root)
{
    if(root==NULL)return;
    res.push_back(root->val);
    preorder(res,root->left);
    preorder(res,root->right);
}
    vector<int> preorderTraversal(TreeNode *root) {
        vector<int> res;
        preorder(res,root);
        return res;
    }
*/
};
原文地址:https://www.cnblogs.com/Vae1990Silence/p/4281221.html