LeetCode 94. 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*> s;
        TreeNode* pos = root;
        while(pos != NULL || !s.empty()){
            while(pos){
                s.push(pos);
                pos = pos -> left;
            }
            TreeNode* cur = s.top();
            s.pop();
            ans.push_back(cur -> val);
            pos = cur -> right;
        }
        return ans;
    }
};

  

posted @ 2020-03-20 17:14  Somnuspoppy  阅读(115)  评论(0编辑  收藏  举报