94. 二叉树的中序遍历


示例:

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

输出: [1,3,2]

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

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 class Solution {
public:
    vector<int> res;
    vector<int> inorderTraversal(TreeNode* root) {
        if(root != nullptr)
        {
             inorderTraversal(root->left);
            res.push_back(root->val);
             inorderTraversal(root->right);
        }
        return res;
    }
};
 */
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        TreeNode* p = root;
        stack<TreeNode*> stack;
        vector<int> res;
        while(p || !stack.empty()){
            if(p){
                stack.push(p);
                p = p->left;
            }
            else{
                TreeNode* q = new TreeNode(-1);
                q = stack.top() ;
                stack.pop();
                res.push_back(q->val);
                p = q->right; 
            }
        }  
        return res;
    }
};
最后修改:2020 年 06 月 20 日 08 : 16 PM
如果觉得我的文章对你有用,那就打发点咯~