【leetcode 144. 二叉树的前序遍历】解题报告

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

方法一:递归

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

方法二:非递归

    vector<int> preorderTraversal(TreeNode* root) 
    {
        vector<int> res;
        if (!root) return res;
        stack<TreeNode*> S;
        TreeNode* p = root;
        while(p||!S.empty())
        {
            if (p)  // 访问左子树
            {
                res.push_back(p->val);
                S.push(p);
                p=p->left;
            }
            else    // 访问右子树
            {
                p=S.top();
                S.pop();
                p=p->right;
            }
        }
        return res;
    }

 方法三:非递归(该方法可用于后序遍历,只需改变一处代码)

    vector<int> res;
    vector<int> preorderTraversal(TreeNode* root) {
        if (!root) return res;
        stack<TreeNode*> S;
        S.push(root);
        while (!S.empty())
        {
            root=S.top();
            S.pop();
            if (root->right) S.push(root->right);  // 要实现后序遍历,需要以下两行调换
            if (root->left) S.push(root->left);
            res.push_back(root->val);   // res.insert(0,root->val)即为后序遍历
        }
        return res;
    }

 结论:

  • 方法三这种形式只适合前序和后序遍历,不适合中序遍历,中序遍历较为麻烦
  • 方法二这种形式只适合前序和中序遍历,不适合后序遍历,后序遍历较为麻烦

猜你喜欢

转载自www.cnblogs.com/brianyi/p/10799458.html