[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
return
Note: Recursive solution is trivial, could you do it iteratively?
解答:
如果采用递归方式来做,思路是很简单的。关键是返回值result的处理:因为不能在preorderTraversal中定义vector<int>,所以定义了临时函数,把result作为一个入口参数传入其中并进行操作。
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作为一个入口参数传入其中并进行操作。
相关文章推荐
- LeetCode-Construct Binary Tree from Preorder and Inorder Traversal-前序中序恢复二叉树-递归
- LeetCode Binary Tree Preorder Traversal 前序遍历二叉树 递归和非递归解法
- [LeetCode] Binary Tree Preorder Traversal (非递归的先序遍历)
- LeetCode: Binary Tree Preorder Traversal 非递归版
- leetcode_105题——Construct Binary Tree from Preorder and Inorder Traversal(树,递归)
- leetcode之Binary Tree Preorder Traversal (前序),中序,后续。非递归,递归
- 【leetcode】非递归先序遍历二叉树(Binary Tree Preorder Traversal)
- leetcode_144题——Binary Tree Preorder Traversal(二叉树,递归,栈的使用)
- [leetcode] Binary Tree Preorder Traversal 非递归先序遍历
- 【LeetCode】Binary Tree Preorder Traversal 二叉树前序遍历递归以及非递归算法
- LeetCode:Binary Tree Preorder Traversal(非递归方法前序遍历二叉树)
- leetcode Construct Binary Tree from Preorder and Inorder Traversal
- Leetcode_144_Binary Tree Preorder Traversal
- Leetcode_105_Construct Binary Tree from Preorder and Inorder Traversal
- leetcode之Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode刷题(C++)——Construct Binary Tree from Preorder and Inorder Traversal(Normal)
- leetcode 109: Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode OJ Construct Binary Tree from Preorder and Inorder Traversal
- leetcode第一刷_Construct Binary Tree from Preorder and Inorder Traversal
- 105. Construct Binary Tree from Preorder and Inorder Traversal LeetCode