#66 Binary Tree Preorder Traversal

来源:互联网 发布:it技术论坛 编辑:程序博客网 时间:2024/06/05 18:34

题目描述:

Given a binary tree, return the preorder traversal of its nodes' values.

Example

Given:

    1   / \  2   3 / \4   5

return [1,2,4,5,3].

题目思路:

还是和#68一样,调一下顺序。

Mycode(AC = 15ms):

/** * 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> ans;        if (root == NULL) return ans;                postorderTraversal(ans, root);        return ans;    }        void postorderTraversal(vector<int>& ans, TreeNode *root) {        if (root == NULL) {            return;        }                // order: root->left->right        ans.push_back(root->val);        postorderTraversal(ans, root->left);        postorderTraversal(ans, root->right);            }};


0 0