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;
}
};