Given a binary tree, return the inorder traversal of its nodes’ values.
给定一棵二叉树,返回它的中序遍历
直接递归解决就可以了,没什么好说的。需要注意的是检查节点值是否为空。
/**
* 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> rootVec;
if (root == NULL) return rootVec;
rootVec.push_back(root->val);
if (root->left) {
vector<int> leftVec = inorderTraversal(root->left);
rootVec.insert(rootVec.begin(), leftVec.begin(), leftVec.end());
}
if (root->right) {
vector<int> rightVec = inorderTraversal(root->right);
rootVec.insert(rootVec.end(), rightVec.begin(), rightVec.end());
}
return rootVec;
}
};