首页 > 其他 > 详细

【leetcode 94. 二叉树的中序遍历】解题报告

时间:2019-05-01 12:35:45      阅读:164      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

前往二叉树的:前序,中序,后序 遍历算法

方法一:递归

    vector<int> res;
    vector<int> inorderTraversal(TreeNode* root) {
        if (!root) return res;
        if (root->left) inorderTraversal(root->left);      
        res.push_back(root->val);
        if (root->right) inorderTraversal(root->right);
        return res;
    }

方法二:非递归

    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();
                S.pop();
                res.push_back(p->val);
                p=p->right;
            }
        }
        return res;
    }

 

【leetcode 94. 二叉树的中序遍历】解题报告

原文:https://www.cnblogs.com/brianyi/p/10799513.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!