Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree
Given binary tree
{1,#,2,3}
,1 \ 2 / 3
return
[1,2,3]
. /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void preorderTra(TreeNode* node, vector<int> &result) {
if(node == NULL) {
return;
}
result.push_back(node->val);
preorderTra(node->left, result);
preorderTra(node->right, result);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
preorderTra(root, result);
return result;
}
};
0 comments:
Post a Comment