Binary Tree DFS遍历专题

本文介绍二叉树后序遍历的应用场景及其实现方法,包括递归和迭代两种方式,并列举了路径总和等典型问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值