剑指offer67题-No24.二叉树中和为某一值的路径(二)

递归,用一个vector存储中间的path路径。

#include <vector>
class Solution {
public:
    // 一个存放最后结果,一个存放临时结果
    vector<vector<int>> res;
    vector<int> path;
    void dfs(TreeNode* root, int target, int temp){
        if(root == nullptr) return;
        path.emplace_back(root->val);
        if(root->left == nullptr && root->right == nullptr && root->val + temp == target){
            res.emplace_back(path);
        }
        dfs(root->left, target, temp + root->val);
        dfs(root->right, target, temp + root->val);
        path.pop_back();
    }
    vector<vector<int> > FindPath(TreeNode* root, int target) {
        if(root == nullptr) return {};
        dfs(root, target, 0);
        return res;
    }
};
  • 时间复杂度:O(n^2),其中n是树的节点数。
  • 空间复杂度:O(n),递归栈的深度不会超过节点数量,但最大可能就是节点数量。

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇