二叉树的中序遍历

来源:互联网 发布:淘宝宝贝排名靠前技巧 编辑:程序博客网 时间:2024/05/21 17:07

容易 二叉树的中序遍历

39%
通过

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

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

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

   1    \     2    /   3

返回 [1,3,2].

挑战

你能使用非递归算法来实现么?

标签 Expand 
递归 二叉树 二叉树遍历








/*** Definition of TreeNode:* class TreeNode {* public:*     int val;*     TreeNode *left, *right;*     TreeNode(int val) {*         this->val = val;*         this->left = this->right = NULL;*     }* }*/class Solution {    /**     * @param root: The root of binary tree.     * @return: Inorder in vector which contains node values.     */     vector<int> ret;     stack<TreeNode *> tmp;public:    vector<int> inorderTraversal(TreeNode *root) {        // write your code here        //tmp.clear();        TreeNode *s = root;        while(!tmp.empty() || s){            while(s){                tmp.push(s);                s = s->left;            }            ret.push_back(tmp.top()->val);            s = tmp.top()->right;            tmp.pop();        }        return ret;    }   };


0 0
原创粉丝点击