二叉树前序遍历

递归:

  void process(TreeNode *root,vector<int> &v){
        if(root == NULL)return;
        v.push_back(root->val);
        process(root->left,v);
        process(root->right,v);
    }
    vector<int> preorderTraversal1(TreeNode *root) {
        vector<int> v;
        process(root,v);
        return v;
    }
非递归

   //非递归
    vector<int> preorderTraversal(TreeNode *root) {
        vector<int> v;
        stack<TreeNode*> s;
        if(root == NULL)return v;
        s.push(root);
        while(!s.empty()){
            TreeNode *t = s.top();
            v.push_back(t->val);
            s.pop();
            if(t->right)s.push(t->right);
            if(t->left)s.push(t->left);
        }
        return v;
    }
原文地址:https://www.cnblogs.com/lyf-sunicey/p/9546975.html