leetcode 94——二叉树的中序遍历
题目描述:
给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
2
/
3
输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
提交一:递归
/**
* 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:
void midOrder(TreeNode* root)
{
if(root!=NULL)
{
midOrder(root->left);
ans.push_back(root->val);
midOrder(root->right);
}
}
vector<int> inorderTraversal(TreeNode* root) {
midOrder(root);
return ans;
}
private:
vector<int> ans;
};
提交二:迭代
/**
* 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) {
if(!root) return ans;
TreeNode* pMove = root;
while(!help.empty()||pMove)
{
//走到最左边,并将走过的路径入栈
while(pMove)
{
help.push(pMove);
pMove=pMove->left;
}
if(!help.empty())
{
pMove = help.top(); help.pop();
ans.push_back(pMove->val);
pMove=pMove->right;
}
}
return ans;
}
private:
vector<int> ans;
stack<TreeNode*> help;
};