Binary Tree DFS traversal contains preorder, inorder and postorder travelsals. In this article, we specifically introduce post-order travelsal, which is useful for a category of problems. In these problems, the traversal path from root to the current node (especially the leaf nodes) should be recorded, and processed by some other routine.
Following is a list of problems belong to this category (more problems to be appended).
1. Path Sum
2. Path Sum II
3. Binary Tree Maximum Path Sum
4. Sum Root to Leaf Numbers
A basic solution to these problems is recursion. Following is the template for recursion.
void dfs(TreeNode *root, vector<int> &path, vector<int> &result)
{
if(root == NULL) return;
path.push_back(root->val)
if //current path meets requirement
result.push_back(path);
if(root->left) dfs(root->left, path, result);
if(root->right) dfs(root->right, path, result);
path.pop_back();
}
If recursion is not permitted, or the problem scale is large and there may be stack overflow, we may choose to implement using our own stack in a iterative style.
For iterative tree traversal, there are three types as mentioned above, the reason we choose post-order is that only in post-order traversal, the root-to-current-node path is preserved perfectly when a node is visited, which is our requirement. Whenever we are visiting a leaf node or the current path meets the result requirement, we collect it and cont. the searching process.
The template based on post-order traversal is as follows.
int iterativeTemplate(TreeNode *root) {
vector<vector<int> > result;
vector<int> path;
if(root == NULL) return result;
vector<TreeNode*> s;
TreeNode *p = root;
TreeNode *prev = NULL;
int num=0, sum=0;
while(p != NULL || !s.empty())
{
if(p != NULL)
{
s.push_back(p);
path.push_back(p->val);
p = p->left;
}
else {
<span style="white-space:pre"> </span> p = s.back();
if (p->right == NULL || p->right == prev)
{
if //the current path meets requirement
result.push_back(path);
path.pop_back();
s.pop_back();
prev = p;
p = NULL;
} else {
p = p->right;
}
}
}
return result;
}