题目链接: 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 getPreOrder(TreeNode *root, vector<int> &preOrder);
vector<int> preorderTraversal(TreeNode *root);
};
void Solution::getPreOrder(TreeNode *root, vector<int> &preOrder) {
if (root != NULL) {
preOrder.push_back(root->val);
getPreOrder(root->left, preOrder);
getPreOrder(root->right, preOrder);
}
}
vector<int> Solution::preorderTraversal(TreeNode *root) {
vector<int> preOrder;
preOrder.clear();
if (NULL == root) {
return preOrder;
}
getPreOrder(root, preOrder);
return preOrder;
}