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

来源:互联网 发布:java bio nio aio详解 编辑:程序博客网 时间:2024/06/04 18:08

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

您在真实的面试中是否遇到过这个题? 
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;    }};


0 0
原创粉丝点击