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

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

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的分支。设计层级计数器难以操作。

全部评论

相关推荐

03-24 16:56
已编辑
肇庆学院 后端
一天代码十万三:你看看人家进大厂的简历就知道了,你这个学历得acm+大厂实习+熟悉底层+运气很好 才有可能进某个大厂,因为大部分是直接卡学历的
投递快手等公司10个岗位
点赞 评论 收藏
分享
程序员牛肉:主要是因为小厂的资金本来就很吃紧,所以更喜欢有实习经历的同学。来了就能上手。 而大厂因为钱多,实习生一天三四百的就不算事。所以愿意培养你,在面试的时候也就不在乎你有没有实习(除非是同级别大厂的实习。) 按照你的简历来看,同质化太严重了。项目也很烂大街。 要么换项目,要么考研。 你现在选择工作的话,前景不是很好了。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务