二叉树的前序遍历-LintCode

来源:互联网 发布:linux jmx监控tomcat 编辑:程序博客网 时间:2024/05/21 14:09

描述:

给出一棵二叉树,返回其节点值的前序遍历。


样例:

给出一棵二叉树 {1,#,2,3},

   1    \     2    /   3

 返回 [1,2,3].

思路:

递归函数。

AC代码:

/** * 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> v;    void front(TreeNode *root)    {        if(root==NULL)            return;        else        {            v.push_back(root->val);            front(root->left);            front(root->right);        }    }    vector<int> preorderTraversal(TreeNode *root) {        // write your code here        front(root);        return v;    }};



0 0