lintcode-二叉树的中序遍历(非递归)-67

给出一棵二叉树,返回其中序遍历

您在真实的面试中是否遇到过这个题?  
Yes
样例

给出二叉树 {1,#,2,3},

   1
    \
     2
    /
   3

返回 [1,3,2]

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
  
public:
    vector<int> inorderTraversal(TreeNode *root) {
        stack<TreeNode*>  s;
        TreeNode *cur=root;
        vector<int> ret;
        
        while(cur||!s.empty()){
            if(cur){
                s.push(cur);
                cur=cur->left;
            }else{
                cur=s.top();
                ret.push_back(cur->val);
                s.pop();
                cur=cur->right;
            }
        }
        return ret;
    }
};


你可能感兴趣的:(lintcode-二叉树的中序遍历(非递归)-67)