二叉树的中序遍历
题目链接
解题思路
- 递归解决
- 先遍历左子树
- 访问根节点
- 再遍历右子树
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode() : val(0), left(nullptr), right(nullptr) {}* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}* };*/
class Solution {
public:vector<int> ans;void def(TreeNode*root){if(root == nullptr) return;if(root->left != nullptr) def(root->left);ans.push_back(root->val);if(root->right != nullptr) def(root->right);}vector<int> inorderTraversal(TreeNode* root) {def(root);return ans;}
};