您的位置:首页 > 其它

[LeetCode] Binary Tree Preorder Traversal [递归版]

2014-05-23 07:29 495 查看
题目:

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

For example:

Given binary tree
{1,#,2,3}
,

1
\
2
/
3


return
[1,2,3]
.

Note: Recursive solution is trivial, could you do it iteratively?
解答:
/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
vector<int> result;
public:
vector<int> preorderTraversal(TreeNode *root) {
return tmpFuction(root, result);
}

vector<int> tmpFuction(TreeNode *root, vector<int> &result) {
if(root == NULL) {
return result;
}
result.push_back(root->val);
tmpFuction(root->left, result);
tmpFuction(root->right, result);
return result;
}
};


如果采用递归方式来做,思路是很简单的。关键是返回值result的处理:因为不能在preorderTraversal中定义vector<int>,所以定义了临时函数,把result作为一个入口参数传入其中并进行操作。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐