剑指offer:面试题34. 二叉树中和为某一值的路径

题目:二叉树中和为某一值的路径

输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。

示例:
给定如下二叉树,以及目标和 sum = 22,

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1
返回:

[
   [5,4,11,2],
   [5,8,4,5]
]


解题:

二叉树的先序遍历的变形,也可以说是DFS

class Solution {
public:
	vector<vector<int>> pathSum(TreeNode* root, int sum) {
		vector<vector<int>> res;
        if(root==NULL) return res;
		vector<int> path;//使用vector作栈,使用它作栈来实现后进能够先出
		FindPath(root, res, path, sum, 0);
		return res;
	}
	void FindPath(TreeNode* root, vector<vector<int>>& res,vector<int>& path,int expectedSum, int currentSum)
	{
        
		currentSum += root->val;
		path.push_back(root->val);
        bool isLeaf=(root->left == NULL&&root->right==NULL);
		if (currentSum==expectedSum&&isLeaf)//如果当前值与给出的值相等,且该结点为叶子节点,则
		{
			res.push_back(path);//该路径入栈
		}
		if (root->left != NULL) FindPath(root->left, res, path, expectedSum, currentSum);
		if (root->right != NULL) FindPath(root->right, res, path, expectedSum, currentSum);
		//返回父节点之前,在路径上删除当前结点
		path.pop_back();
	}
};

发布了106 篇原创文章 · 获赞 113 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/qq_41598072/article/details/104582519
今日推荐