94. Binary Tree Inorder Traversal

思路
用一个stack解决问题。先尽可能往左地把节点放入栈。
每次取出节点并访问,再对它的右节点尽可能往左地放入栈即可。
详情

/**
 * 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 inorderTraversal(TreeNode* root) {
        stack st;
        vector res;
        
        TreeNode *n = root;
        while (n) {
            st.push(n);
            n = n->left;
        }
        
        while (!st.empty()) {
            TreeNode *cur = st.top();
            st.pop();
            res.push_back(cur->val);
            
            TreeNode *r = cur->right;
            while(r) {
                st.push(r);
                r = r->left;
            }
        }
        
        return res;
    }
};

你可能感兴趣的:(94. Binary Tree Inorder Traversal)