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

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

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

全部评论

相关推荐

泥给路哒油:真的不行了,以后趋势就是没有前后端职位之分了,我现在就是什么都干,有了ai就能干全栈,md年初目送一大堆同事毕业
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
正在热议
更多
# 春招至今,你的战绩如何? #
8454次浏览 76人参与
# 你的实习产出是真实的还是包装的? #
1557次浏览 39人参与
# 巨人网络春招 #
11282次浏览 223人参与
# 军工所铁饭碗 vs 互联网高薪资,你会选谁 #
7300次浏览 40人参与
# 简历第一个项目做什么 #
31444次浏览 320人参与
# 当下环境,你会继续卷互联网,还是看其他行业机会 #
186719次浏览 1118人参与
# MiniMax求职进展汇总 #
23616次浏览 305人参与
# 不考虑薪资和职业,你最想做什么工作呢? #
152201次浏览 887人参与
# 研究所笔面经互助 #
118829次浏览 577人参与
# 重来一次,我还会选择这个专业吗 #
433235次浏览 3926人参与
# 简历中的项目经历要怎么写? #
309862次浏览 4177人参与
# 面试紧张时你会有什么表现? #
30460次浏览 188人参与
# 你今年的平均薪资是多少? #
212910次浏览 1039人参与
# AI时代,哪些岗位最容易被淘汰 #
63173次浏览 784人参与
# 我的求职精神状态 #
447925次浏览 3128人参与
# 你最满意的offer薪资是哪家公司? #
76352次浏览 374人参与
# 正在春招的你,也参与了去年秋招吗? #
363053次浏览 2635人参与
# 你怎么看待AI面试 #
179703次浏览 1220人参与
# 牛客AI文生图 #
21391次浏览 237人参与
# 职能管理面试记录 #
10773次浏览 59人参与
# 网易游戏笔试 #
6422次浏览 83人参与
# 腾讯音乐求职进展汇总 #
160527次浏览 1109人参与
牛客网
牛客网在线编程
牛客网题解
牛客企业服务