1、问题描述
给出一棵二叉树,返回其中序遍历,给出二叉树 {1,#,2,3},
1
\
2
/
3
返回 [1,3,2].
2、实现思路
与前序遍历类似。若二叉树为空,则空操作返回。否则中序遍历根节点的左子树,访问根节点,中序遍历根节点的右子树。
3、代码
/**
* 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> p;
if(root==NULL) return p;
zhongxubianli(p,root);
return p;
}
private:
void zhongxubianli(vector<int>& p,TreeNode* root)
{
if(root==NULL)return;
zhongxubianli(p,root->left);
p.push_back(root->val);
zhongxubianli(p,root->right);
}
};
4、感想
利用递归进行中序遍历,注意需要再写一个中序遍历函数,因为原函数每次递归vector<int> p都会初始化vector, 用原函数调用中序遍历函数,结束条件为NULL。