面试题25 :二叉树中和为某一值的路径

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/okiwilldoit/article/details/78518424

一. Leetcode-129:Sum Root to Leaf Numbers

首先看下一道比较简单的题目,输入一个二叉树,输出所有路径代表的十进制数之和。

一般二叉树类的题目,肯定要用到递归函数。
本题中

递归函数的参数有三个:root,total_sum(引用传递,即最终结果), sum(单条路径的和)

递归函数的跳出条件为遍历到叶子节点,返回前要把sum加到total_sum上。

int sumNumbers(TreeNode* root) {
    int total_sum = 0;
    sumNumbersHelper(root, total_sum, 0);
    return total_sum;
}

void sumNumbersHelper(TreeNode* root, int &total_sum, int sum)
{
    if(root ==  NULL)
    {
        return;
    }

    sum = sum*10 + root->val;

    if(root->left == NULL && root->right == NULL)
    {
        total_sum += sum;
        return;
    }

    if(root->left != NULL)
    {
        sumNumbersHelper(root->left, total_sum, sum);
    }

    if(root->right != NULL)
    {
        sumNumbersHelper(root->right, total_sum, sum);
    }   
}

二. Leetcode-113 Path Sum II

本题即面试题25。Leetcode-112的Path Sum比本题要简单,只需确定是否能够找到这样一条路径,使其和等于给出值。
而本题需要的是找出所有路径,并打印出来(也就是返回vector)。

与上题类似,同样用递归,辅助递归函数的参数比较多,有五个:

根节点,目标sum值,一条路径当前sum值,结果集(最终结果,引用传递),一条路径集合(引用传递)

递归的终止条件同样是遍历到叶子节点,返回前要判断这条路径之和是否等于目标sum值。

注意的是,递归完成后,要把list中的最后一个数删除。深度遍历,遍历到叶子节点后(即得到一个答案后),要返回到该叶子节点的父节点,所以要把该list中的最后一个数删除。如二叉树(1,2,1,#,#,1,#),输入的参数是3,遍历到2时,得到一个list={1,2},然后要返回节点1,即pop_back 2 ,然后继续遍历得到另一个答案list={1,1,1}。

vector<vector<int>> pathSum(TreeNode* root, int sum) {
    vector<vector<int>> lists;
    if(root == NULL)
    {
        return lists;
    }
    vector<int> one_list;
    int cur_sum = 0;
    pathSumHelper(root, sum, cur_sum, lists, one_list);
    return lists;
}

void pathSumHelper(TreeNode* root, int sum, int cur_sum, vector<vector<int>> &lists, vector<int> &one_list)
{
    if(root == NULL)
    {
        return;
    }

    cur_sum += root->val;
    one_list.push_back(root->val);

    //遍历到叶子节点
    if(root->left==NULL && root->right==NULL)
    {
        if(cur_sum == sum)
        {
            lists.push_back(one_list);
        }
        //已到叶子节点,结束
        return;
    }

    //遍历左子树
    if(root->left != NULL)
    {
        pathSumHelper(root->left, sum, cur_sum, lists, one_list);
        one_list.pop_back();
    }

    //遍历右子树
    if(root->right != NULL)
    {
        pathSumHelper(root->right, sum, cur_sum, lists, one_list);
        one_list.pop_back();
    }        
}

猜你喜欢

转载自blog.csdn.net/okiwilldoit/article/details/78518424