1. 程式人生 > 實用技巧 >P3975 [TJOI2015]弦論

P3975 [TJOI2015]弦論

型別一:給定二叉樹,求其前序遍歷、中序遍歷、後序遍歷(迭代解法)

前序遍歷:(思路:用一個棧儲存待遍歷的節點)

vector<int> preorderTraversal(TreeNode* root) {
        vector<int> output;
        if(root==NULL)
            return output;
        vector<TreeNode *> V;
        stack<TreeNode *> S;
        TreeNode *ptemp = root;
        V.push_back(root);
        while(!S.empty()||ptemp->left!=NULL||ptemp->right!=NULL)
        {
            if(ptemp->right!=NULL&&ptemp->left != NULL)
            {
                S.push(ptemp->right);
                V.push_back(ptemp->left);
            }
            else if(ptemp->left != NULL)
                V.push_back(ptemp->left);
            else if(ptemp->right != NULL)
                V.push_back(ptemp->right);
            else
            {
                    V.push_back(S.top());
                    S.pop();
            }
            ptemp = V.back();
        }
        for(auto it:V)
        {
            output.push_back(it->val);
        }
        return output;
    }

中序遍歷:(未經驗證,可能存在bug)

vector<int> midorderTraversal(TreeNode* root)
{
	vector<int> output;
	if (root == NULL)
		return output;
	vector<TreeNode*> V;
	stack<TreeNode*> S_root, S_right;
	TreeNode* ptemp = root;
	while (!S_root.empty() || !S_right.empty() || ptemp->left != NULL || ptemp->right != NULL)
	{
		if (ptemp->left != NULL && ptemp->right != NULL)
		{
			S_right.push(ptemp->right);
			S_root.push(ptemp);
			ptemp = ptemp->left;
		}
		else if (ptemp->left != NULL)
		{
			S_root.push(ptemp);
			ptemp = ptemp->left;
		}
		else if (ptemp->right != NULL)
		{
			V.push_back(ptemp);
			ptemp = ptemp->right;
		}
		else
		{
			V.push_back(ptemp);
			if (!S_root.empty())
			{
				ptemp = S_root.top();
				while (ptemp->right == NULL)
				{
					V.push_back(ptemp);
					S_root.pop();
					if (!S_root.empty())
						ptemp = S_root.top();
					else
						break;
				}
				V.push_back(ptemp);
				S_root.pop();
			    ptemp = S_right.top();
				S_right.pop();
			}
		}
	}
}