问题描述:给出一棵二叉树,返回其中序遍历
样例:
给出二叉树 {1,#,2,3}
,
1 \ 2 / 3
返回 [1,3,2]
.
实现思路:由二叉树中序遍历的操作定义,用递归算法访问二叉树的节点,并将访问的节点的值存放在向量v中,返回向量v。
实现代码:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
/**
* @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
vector<int> v;
in(v,root);
return v;
}
void in(vector<int> &v,TreeNode *root){
if(root==NULL)
return;
else{
in(v,root->left);
v.push_back(root->val);
in(v,root->right);
}
}
};