leetcode 94. 二叉树的中序遍历

1. 题目描述

1
2
3
4
5
6
7
8
9
10
11
12
给定一个二叉树,返回它的中序遍历。
示例:
输入: [1,null,2,3]
1
2
/
3
输出: [1,3,2]

2. 思路

典型的中序遍历代码

3. 代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
helper(root, res);
return res;
}
void helper(TreeNode* root, vector<int>& res) {
if (root == nullptr)
return;
if (root->left)
helper(root->left, res);
res.push_back(root->val);
if (root->right)
helper(root->right, res);
}
};