二叉树——94. 二叉树的中序遍历
题目:
思路:
就递归啊,套模板,别想迭代了,迭代还要借助栈直接考虑递归,老舒服了。记着中序遍历的顺序就是:左中右,这是我们单层递归的逻辑。
代码:
class Solution {
public:
void inorder(TreeNode* root, vector<int>& res) {
// 为空直接返回,终止条件。
if (!root) {
return;
}
inorder(root->left, res); // 左
res.push_back(root->val); // 中
inorder(root->right, res); // 右
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
inorder(root, res);
return res;
}
};