二叉树的中序遍历
题目链接:二叉树的中序遍历
给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。
方法一:中序遍历
/**
* 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:
void inorder(TreeNode* root,vector<int>& v) {
if (root == nullptr) return;
inorder(root->left,v);
v.push_back(root->val);
inorder(root->right,v);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ans;
inorder(root,ans);
return ans;
}
};