• [leetcode-113-Path Sum II]


    Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
    For example:
    Given the below binary tree and sum = 22,
          5
         /
        4 8
       / /
     11 13 4
     / /

    7 2 5 1
    return
    [
    [5,4,11,2],
    [5,8,4,5]
    ]
    Subscribe to see which companies asked this question.

    思路:

    保存当前遍历的路径,判断当前是否到达根部,而且路径和是否与sum相等。

    如果满足条件,将当前路径保存到最后结果里。

    如果不满足,先进入左子树 然后右子树判断 ,判断完左子树和右子树后,把开始保存的路径值弹出,向上进行回溯。

        void pathSum(TreeNode* root, int sum, vector<vector<int>>& result,vector<int>&path)
        {
            if (root == NULL) return;
            path.push_back(root->val);//暂时放入当前路径中保存
            if (root->left == NULL && root->right == NULL && root->val == sum)//找到路径
            {
                result.push_back(path);
            }
            pathSum(root->left, sum - root->val, result, path);
            pathSum(root->right,sum - root->val, result, path);
    
            path.pop_back();//弹出 回溯
        }
        vector<vector<int>> pathSum(TreeNode* root, int sum)
        {
            vector<vector<int>> result;
            vector<int> path; 
            
            pathSum(root, sum, result, path);
            return result;
        }

     参考:

    https://discuss.leetcode.com/topic/18454/12ms-11-lines-c-solution

  • 相关阅读:
    表单:文本框默认提示信息(小例子)
    代码:jquery小效果—— 吸顶
    Day5:面向对象的定义(中)
    Day5:面向对象的定义(上)
    Day4:数组(扩展知识)
    Day4:数组
    Day3:JAVA方法的定义
    Day2:JAVA判断与运算(循环)
    Eclipse使用技巧
    (HTTP)状态码详解
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6489146.html
Copyright © 2020-2023  润新知