题目来源:leetcode94 二叉树的中序遍历
题目描述:
给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
输出: [1,3,2]
解题思路:
借助栈来解决
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ans;
stack <TreeNode* > s;
while(!s.empty()||root!=NULL){
if(root==NULL){
TreeNode* t=s.top();
s.pop();
ans.push_back(t->val);
if(t->right) root=t->right;
}
else
{
s.push(root);
root=root->left;
}
}
return ans;
}
};