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

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

https://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca?tpId=265&rp=1&ru=%2Fexam%2Foj%2Fta&qru=%2Fexam%2Foj%2Fta&sourceUrl=%2Fexam%2Foj%2Fta%3FjudgeStatus%3D3%26page%3D1%26pageSize%3D50%26search%3D%26tpId%3D13%26type%3D265&difficulty=&judgeStatus=3&tags=&title=&gioEnter=menu

一开始递归没有处理好,相比较(一)来说不能原地递归,同时需要回溯

/*
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) {
      std::vector<std::vector<int>> res;
      std::vector<int> tmp;
      
      if (root == nullptr) {
        return res;
      }
      
      curision(root, expectNumber, res, tmp);
      
      return res;
    }
  private:
    void curision(TreeNode *root, int num, std::vector<std::vector<int>> &res, std::vector<int> &tmp) {
      //  找到是不会遍历到空节点的
      if (root == nullptr) {
        return ;
      }
      
      tmp.push_back(root->val);
      num -= root->val;
      
      //  需要一直遍历到空节点,才能正确回溯,不能中途返回
      if (num == 0 && root->left == nullptr && root->right == nullptr) {
        res.push_back(tmp);
      }
      
      curision(root->left, num, res, tmp);
      curision(root->right, num, res, tmp);
      //  回溯
      tmp.pop_back();
    }
};
全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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