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:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ans;
if(root==NULL)
return ans;
stack<TreeNode*> stk;
TreeNode *cur=root;
while(!stk.empty()||cur){
while(cur){
stk.push(cur);
cur=cur->left;
}
cur=stk.top();
stk.pop();
ans.push_back(cur->val);
cur=cur->right;
}
return ans;
}
};