剑指Offer第二十四题:二叉树中和为某一值的路径

版权声明:欢迎交流,本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_42513339/article/details/89083920

题目描述

输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)

思路:这里需要用到深度优先搜索,每次进入下一层时,先记录前几层的数据,然后判断这一层是否是叶子节点,并这条路径和为需要的数。都符合就添加这个数组。还是需要用到递归。

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    vector<vector<int> > FindPath(TreeNode* root,int expectNumber){
        vector<vector<int> >ans;
        vector<int>my;
        if(root)
            dfs(root,expectNumber,ans,my);
        BubbleSort(ans,ans.size());//个人认为还是需要最后排序一下,这里直接用了冒泡
        return ans;
    }

    void dfs(TreeNode* root,int ex,vector<vector<int> >& ans,vector<int>my)
    {
        my.push_back(root->val);
        if(ex - root->val==0 && root->left == NULL && root->right == NULL)
            ans.push_back(my);       
        
        if(root->left != NULL)
            dfs(root->left,ex - root->val, ans,my);
        if(root->right != NULL)
            dfs(root->right,ex - root->val, ans,my);
        
    }
    
    void BubbleSort(vector<vector<int> >& ans,int n)
    {
        for(int i = 0; i<n-1;i++)
        {
            for(int j = 0; j < n-1-i;j++)
            {
                if(ans[j].size()<ans[j+1].size())
                    ans[j].swap(ans[j+1]);
            }
        }
    }  
};

猜你喜欢

转载自blog.csdn.net/weixin_42513339/article/details/89083920