LeetCode 94. Binary Tree Inorder Traversal

时间:2019-09-25
本文章向大家介绍LeetCode 94. Binary Tree Inorder Traversal,主要包括LeetCode 94. Binary Tree Inorder Traversal使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

没什么好说的,就是一道中序遍历题。  当然,使用了递归,效率肯定就那样,那些效率高的,都是通过迭代写的。

 1 class Solution {
 2 public:
 3     vector<int> inorderTraversal(TreeNode* root) {
 4         vector<int> v;
 5         if(root!=NULL){
 6             vector<int> v1=inorderTraversal(root->left);
 7             copy(v1.begin(),v1.end(),back_inserter(v));
 8             v.push_back(root->val);
 9             v1=inorderTraversal(root->right);
10             copy(v1.begin(),v1.end(),back_inserter(v));
11         }
12         return v;
13     }
14 };

熟悉一下STL的copy和back_inserter():

1 template <class InputIterator, class OutputIterator>
2 OutputIterator copy (InputIterator first, InputIterator last,OutputIterator result);

copy:将 [ first , last ) 的内容拷贝到result中。

1 template <class Container>
2 back_insert_iterator<Container> back_inserter (Container& x);

back_inserter:返回一个指向x的尾部插入迭代器,作为输入迭代器,用于输入。

原文地址:https://www.cnblogs.com/yy-1046741080/p/11583719.html