TreeNode* Algorithm::pruneTree(TreeNode* root)
{
bool bCut = true;
while (bCut)
{
std::stack<TreeNode*> stRoot;
TreeNode* pCur = root;
TreeNode* pPre = nullptr;
stRoot.push(root);
bCut = false;
while (!stRoot.empty())
{
pCur = stRoot.top();
TreeNode* pLeft = pCur->left;
TreeNode* pRight = pCur->right;
if (pLeft != NULL)
{
if (pLeft->left == NULL && pLeft->right == NULL && pLeft->val == 0)
{
delete pLeft;
pCur->left = NULL;
bCut = true;
}
}
if (pRight != NULL)
{
if (pRight->left == NULL && pRight->right == NULL && pRight->val == 0)
{
delete pRight;
pCur->right = NULL;
bCut = true;
}
}
if (bCut)
{
break;
}
if ((pCur->left == NULL && pCur->right == NULL) || (pPre != NULL && (pPre == pCur->left || pPre == pCur->right)))
{
stRoot.pop();
pPre = pCur;
}
else
{
if (pCur->right != NULL)
{
stRoot.push(pCur->right);
}
if (pCur->left != NULL)
{
stRoot.push(pCur->left);
}
}
}
}
return root;
}
本题解法的关键是使用非递归的方式,后续遍历二叉树;非递归的关键是使用栈;