Binary Tree 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> res;
    void dfs(TreeNode *root){
        if(!root) return;
        res.push_back(root->val);
        dfs(root->left);
        dfs(root->right);
    }
    vector<int> preorderTraversal(TreeNode *root) {
        dfs(root);
        return res;
    }
};

 

posted @ 2015-03-16 21:11  SprayT  阅读(67)  评论(0编辑  收藏  举报