zoukankan      html  css  js  c++  java
  • 剑指offer之【二叉树中和为某一值的路径】

    题目:

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

    链接:

      https://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca?tpId=13&tqId=11177&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

    题目描述:

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

    思路:

      进行扫描,扫描到叶子节点后,看是否符合和为目标值的要求,如符合加入结果中,如不符合继续扫描。

    代码:

      

     1 /*
     2 struct TreeNode {
     3     int val;
     4     struct TreeNode *left;
     5     struct TreeNode *right;
     6     TreeNode(int x) :
     7             val(x), left(NULL), right(NULL) {
     8     }
     9 };*/
    10 class Solution{
    11 public:
    12     vector<vector<int>> FindPath (TreeNode *root,int expectNumber){
    13         if(root == nullptr || expectNumber < 0)
    14               return res;
    15         sumpath(root,expectNumber);
    16         return res;
    17     }
    18     void sumpath(TreeNode *root ,int expectNumber){
    19         if(root ==nullptr)
    20             return ;
    21         path.push_back(root->val);
    22         expectNumber -= root->val;
    23         if(root->left == nullptr && root ->right == nullptr && expectNumber == 0){
    24             res.push_back(path);
    25         }
    26         sumpath(root->left,expectNumber);
    27         sumpath(root->right,expectNumber);
    28         path.pop_back();
    29     }
    30 private:
    31     vector<vector<int>> res;
    32     vector<int> path;
    33 };
  • 相关阅读:
    日期插件,年月,年月日,时分,年月时分
    <context:annotation-config/>
    Autowired注解
    context:component-scan 注解的扫描
    Servlet 是什么 有哪些类
    spring RestTemplate 出现 NoHttpResponseException 和 ConnectionTimeoutException
    java 动态加载groovy 脚本
    java 如何实现文件变动的监听
    英文文档地址
    Resource ResourceLoader
  • 原文地址:https://www.cnblogs.com/wangshujing/p/6938348.html
Copyright © 2011-2022 走看看