首页 > 代码库 > binary-tree-inorder-traversal

binary-tree-inorder-traversal

/**
 * Definition for binary tree
 * 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> res;
        if(!root)
            return res;
        
        stack<TreeNode *> s;
        TreeNode * p = root;
        
        while(p || !s.empty()){
            if(p){
                s.push(p);
                p = p->left;
            }
            else{
                p = s.top();
                res.push_back(p->val);
                s.pop();
                p = p->right;
                }
            }
        
        return res;
       }
   
};

 

binary-tree-inorder-traversal