当你的才华还撑不起你的野心时,你应该静下心去学习 。
题目描述
输入一颗二叉树的根节点和一个整数,按字典序打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
输入
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
输出
[
[5,4,11,2],
[5,8,4,5]
]
解题思路
先序遍历: 按照 “根、左、右” 的顺序,遍历树的所有节点。 路径记录: 在先序遍历中,记录从根节点到当前节点的路径。当路径为 ① 根节点到叶节点形成的路径 且 ② 各节点值的和等于目标值 sum 时,将此路径加入结果列表。
时间复杂度 O(N) : NN 为二叉树的节点数,先序遍历需要遍历所有节点。 空间复杂度 O(N) : 最差情况下,即树退化为链表时,path 存储所有树节点,使用 O(N) 额外空间。
class Solution {
LinkedList res = new LinkedList();
LinkedList path = new LinkedList();
public List pathSum(TreeNode root, int sum) {
recur(root, sum);
return res;
}
void recur(TreeNode root, int tar) {
if(root == null) return;
path.add(root.val);
tar -= root.val;
if(tar == 0 && root.left == null && root.right == null)
res.add(new LinkedList(path));
recur(root.left, tar);
recur(root.right, tar);
path.removeLast();
}
}
// 关注TechGuide,大厂笔经面经闪电速递!
CPP版本
class Solution {
public:
vector res;
vector path;
vector pathSum(TreeNode* root, int sum) {
helper(root ,sum);
return res;
}
private:
void helper(TreeNode* root , int sum){
if(root == nullptr) return;
path.push_back(root -> val);
sum -= root -> val;
if(sum == 0 && root -> left == nullptr && root -> right == nullptr){
res.push_back(path);
}
helper(root -> left ,sum);
helper(root -> right ,sum);
path.pop_back();
}
}
// 关注TechGuide,大厂笔经面经闪电速递!
创作不易,你的鼓励是我创作的动力,如果你有收获,点个赞吧👍