问题描述:
给出一颗二叉树,返回其中序遍历。
实现思路:
创建动态数组来存放节点的值。利用递归的方法。
实现代码:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
std::vector<int> v;
/**
* @param root: The root of binary tree.
* @return: Inorder in vector which contains node values.
*/
public:
vector<int> inorderTraversal(TreeNode *root) {
// write your code here
if (root != NULL)
{
inorderTraversal(root->left);
v.push_back(root->val);
inorderTraversal(root->right);
}
return v;
}
};
感想:
中序遍历和前序遍历类似,利用递归。考虑root为空的情况。