94、二叉树的中序遍历
原题连接:https://leetcode.cn/problems/binary-tree-inorder-traversal/
问题描述:
给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。
示例 1:
输入:root = [1,null,2,3]
输出:[1,3,2]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [1]
输出:[1]
提示:
树中节点数目在范围 [0, 100] 内
-100 <= Node.val <= 100
C++递归:
class Solution {
public:
void inorder(TreeNode * root , vector<int> &x){
if(root == NULL){
//当走到的某个节点为空时,就返回上一个函数调用
return;
}
inorder(root->left , x); //利用递归先走左边
x.push_back(root -> val); //记录下有数值的节点
inorder(root->right , x); //利用递归走右边
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
inorder(root , res); //传入树与vector容器
return res;//返回vector容器
}
};