没什么好说的,递归解决。
/**
* Definition for binary tree
* 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;
if (root == NULL)
return res;
if (root->left != NULL) {
vector<int> t1 = inorderTraversal(root->left);
res.insert(res.end(), t1.begin(), t1.end());
}
res.push_back(root->val);
if (root->right != NULL) {
vector<int> t2 = inorderTraversal(root->right);
res.insert(res.end(), t2.begin(), t2.end());
}
return res;
}
};
稍微简洁点的:
/**
* Definition for binary tree
* 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> &path) {
if (root == NULL)
return;
helper(root->left, path);
path.push_back(root->val);
helper(root->right, path);
}
};
http://oj.leetcode.com/problems/binary-tree-inorder-traversal/