left_tree = inorderTraversal(root->left); right_tree = inorderTraversal(root->right); res_tree.insert(res_tree.end(), left_tree.begin(), left_tree.end());
时间: 2024-02-12 22:07:17 浏览: 66
这段代码是二叉树中序遍历的代码,将左子树和右子树的遍历结果分别存储在`left_tree`和`right_tree`中,然后将`left_tree`中的元素插入到结果数组`res_tree`的末尾。具体来说,`res_tree.insert(res_tree.end(), left_tree.begin(), left_tree.end());`这一行代码的作用是将`left_tree`中的所有元素插入到`res_tree`的末尾。
这段代码的完整作用是遍历一个二叉树,将其中序遍历的结果存储在`res_tree`中。
示例:
```cpp
#include <iostream>
#include <vector>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
std::vector<int> inorderTraversal(TreeNode* root) {
std::vector<int> res_tree;
if (root == nullptr) {
return res_tree;
}
std::vector<int> left_tree, right_tree;
left_tree = inorderTraversal(root->left);
right_tree = inorderTraversal(root->right);
res_tree.insert(res_tree.end(), left_tree.begin(), left_tree.end());
res_tree.push_back(root->val);
res_tree.insert(res_tree.end(), right_tree.begin(), right_tree.end());
return res_tree;
}
};
int main() {
TreeNode *root = new TreeNode(1);
root->right = new TreeNode(2);
root->right->left = new TreeNode(3);
Solution s;
std::vector<int> res = s.inorderTraversal(root);
for (auto i : res) {
std::cout << i << " ";
}
return 0;
}
```
输出结果为:
```
1 3 2
```
阅读全文