当前位置: 代码迷 >> 综合 >> 剑指Offer JZ23 二叉树中和为某一值的路径 C++实现
  详细解决方案

剑指Offer JZ23 二叉树中和为某一值的路径 C++实现

热度:56   发布时间:2024-02-22 07:18:48.0

题目描述

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

解题思路


方法一:递归

1、思路:先序遍历,在遍历的过程中,先将当前结点值入栈,然后判断:

  • 当前结点是叶子结点且其值等于所期望的值,则这条路径合法,保存此路径上的所有结点值;
  • 当前结点不是叶子结点,递归判断其左子树和右子树,注意期望值要减去当前结点值;

回溯时表明已经不需要当前结点,结点值需要出栈。

2、代码:

/*
struct TreeNode {int val;struct TreeNode *left;struct TreeNode *right;TreeNode(int x) :val(x), left(NULL), right(NULL) {}
};*/
class Solution {
public:void path(TreeNode* root, int expect, vector<int> &singlePath, vector<vector<int> > &result) {singlePath.push_back(root->val);if (!root->left && !root->right && root->val == expect) {result.push_back(singlePath);}if (root->left) path(root->left, expect - root->val, singlePath, result);if (root->right) path(root->right, expect - root->val, singlePath, result);singlePath.pop_back();}vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {vector<vector<int> > result;vector<int> singlePath;if (!root || !expectNumber || root->val > expectNumber)return result;path (root, expectNumber, singlePath, result);return result;}
};

3、复杂度:

时间复杂度:O(n),遍历一次树的所有结点;

空间复杂度:O(n),当树退化为链表,递归空间为O(n)。

  相关解决方案