brianyi

 

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

方法一:递归

    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;
    }

 

分类:

技术点:

相关文章:

  • 2021-08-17
  • 2021-12-29
  • 2021-12-25
  • 2021-12-18
  • 2022-01-17
  • 2021-07-29
  • 2021-07-23
猜你喜欢
  • 2021-07-27
  • 2021-08-29
  • 2021-06-26
  • 2022-01-30
  • 2021-07-07
  • 2022-12-23
  • 2021-09-02
相关资源
相似解决方案