题解 | #二叉树中和为某一值的路径(二)#

二叉树中和为某一值的路径(二)

https://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca

/*
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) {
        //keep scanning
		//when reaches the leaf and the sum equals to expect number,it means a satisfied path is found
		//insert new array.

		//when back to a non-leaf node,if there are arrays in the vector  and the number of element is less than the depth,it means its in the back path.
		//new

		//scan and push.when reaches the leaf
		//if the sum equals,push to the return vector,if not,pop it back.
		
		vector<vector<int>> ret;
		vector<int> paths;
		int sum=0;
		dfs(root,expectNumber,ret,paths,sum);

		return ret;

    }
	void dfs(TreeNode * root,int expectNumber,vector<vector<int>> & ret,vector<int> & paths,int sum){

		if(root==nullptr)
			return ;
		//visit the current node,push it and calcualte the sum
		paths.push_back(root->val);
		sum+=root->val;

		//process the end
		if(root->left==nullptr && root->right==nullptr){
			//reaches the end
	 
			if(sum==expectNumber){
				ret.push_back(paths);
			}
		}
		else{
			dfs(root->left,expectNumber,ret,paths,sum);
			dfs(root->right,expectNumber,ret,paths,sum);
		}

		//when finishing visiting a node, pop it back
		paths.pop_back();
		sum-=root->val;
		return ;
	}
};

最初思路是探底,符合再自低向上加。

这个过程可以修改为探底的中途增加,符合条件算进返回结果。否则弹出。这样的优点是,返回的时候结果可以复用。

否则由于先访问叶子再返回根的特点,会引入很多空vector,回加。不如在到达叶子结点时就push ret

因为需要处理在返回途中进入另一个不符合expect number的分支。设计层级计数器难以操作。

全部评论

相关推荐

但听说转正率很低,我现在有在实习了,好纠结要不要去
熬夜脱发码农:转正率低归低,但是实习的经历你可以拿着,又不是说秋招不准备了
点赞 评论 收藏
分享
下个早班:秒挂就是不缺人
点赞 评论 收藏
分享
自学java狠狠赚一...:骗你点star的,港卵公司,记得把star收回去
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-03 17:37
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务