Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree [1,null,2,3]
,
1 \ 2 / 3
return [1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
二叉树的 中序遍历
/**
* 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> a;
if(root==NULL)return a;
fun(a,root);
return a;
}
void fun(vector<int> &x,TreeNode* root)
{
if(root==NULL) return ;
fun(x,root->left);
x.push_back(root->val);
fun(x,root->right);
}
};
根据中序遍历要求先遍历左子树 再遍历自己 然后遍历右子树 下面我采用的是递归方法实现要求
void fun(vector<int> &x,TreeNode* root)
{
if(root==NULL) return ;
fun(x,root->left);
x.push_back(root->val);
fun(x,root->right);
}