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) {}
 * };
 */
 
vector<int> inorderTraversal(TreeNode *root) 
{
    vector<int> ret;
    stack<TreeNode *> s;
    TreeNode *p = root;
    
    do
    {
        while (p != NULL)
        {
            s.push(p);
            p = p->left;
        }
        
        if (!s.empty())
        {
            p = s.top();
            s.pop();
            
            ret.push_back(p->val);
            
            p = p->right;
        }
    } while (!s.empty() || p != NULL);
    
    return ret;
}
posted @ 2012-09-01 17:10  紫红的泪  阅读(1477)  评论(0编辑  收藏  举报