首页 > 代码库 > Binary Tree Preorder Traversal

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:    void PreOrder(TreeNode* root,vector<int>&vec)    {        if(root!=NULL)        {            vec.push_back(root->val);            PreOrder(root->left,vec);            PreOrder(root->right,vec);        }    }    vector<int> preorderTraversal(TreeNode *root)    {         vector<int>vec;         PreOrder(root,vec);         return vec;    }};