lintcode 二叉树前序遍历

时间:2023-03-10 04:17:32
lintcode 二叉树前序遍历
二叉树的前序遍历 

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

您在真实的面试中是否遇到过这个题?
Yes
样例

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

   1
\
2
/
3

返回 [1,2,3].

 /**
* 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: A Tree
* @return: Preorder in ArrayList which contains node values.
*/ void inorder (TreeNode *root, vector<int> &result) {
result.push_back(root->val);
if (root->left != NULL) {
inorder(root->left, result);
} if (root->right != NULL) {
inorder(root->right, result);
}
} vector<int> preorderTraversal(TreeNode * root) {
// write your code here
vector<int> result;
if (root == NULL) {
return result;
}
inorder(root, result);
return result;
}
};