leetcode(33)--中序遍历二叉树

送分小仙女□ 提交于 2020-02-11 21:19:57

题目:

给定一个二叉树,返回它的中序 遍历。

示例:

输入: [1,null,2,3]
   1
    \
     2
    /
   3

输出: [1,3,2]

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

思路:非迭代方法

class Solution {
public:
   vector<int> inorderTraversal(TreeNode *root)
{   vector<int> res;
    stack<TreeNode *> s;
    TreeNode *p = root;
    while(p != NULL || !s.empty())
    {
        while(p != NULL)
        {
            s.push(p);
            p = p->left;
        }
        if(!s.empty())
        {
            p = s.top();
            res.push_back(p->val);
            s.pop();
            p = p->right;
        }

    }
 return res;
}
};

思路2:迭代方法

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        inorder(root,res);
        return res;
    }
    void inorder(TreeNode* p, vector<int>& res)
    {
        if(p!=NULL)
        {
            inorder(p->left,res);
            res.push_back(p->val);
            inorder(p->right,res);
        }
    }
};

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!