1.题目
给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3输出: [1,3,2]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.code
2.1递归版本
/**
* 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>v;
vector<int> inorderTraversal(TreeNode* root) {
vector<int>t;
if(root==NULL)
return v;
if(root!=NULL)
{
t=inorderTraversal(root->left);
v.push_back(root->val);
t=inorderTraversal(root->right);
}
return v;
}
};
2.2非递归版本
/**
* 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>v;
stack<TreeNode*>s;
TreeNode *tree;
tree=root;
if(root==NULL)
return v;
while(tree||!s.empty())
{
while(tree)
{
s.push(tree);
tree=tree->left;
}
if(!s.empty())
{
tree=s.top();
v.push_back(tree->val);
s.pop();
tree=tree->right;
}
}
return v;
}
};