zoukankan      html  css  js  c++  java
  • Path Sum II (Find Path in Tree) -- LeetCode

    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]
    ]
     
    思路:简单的DFS。要注意的一点是,所有的路径必须到达叶子结点才算数。叶子结点的定义是没有孩子的节点。假如root节点没有孩子节点,则root节点就算是叶子结点。但当root节点有一个左孩子节点却没有右孩子节点时,它就不能算是叶子节点了。
     1 class Solution {
     2 public:
     3     void help(vector<vector<int> >& res, TreeNode* root, vector<int>& path, int target)
     4     {
     5         TreeNode *left = root->left, *right = root->right;
     6         path.push_back(root->val);
     7         if (!left && !right && target == root->val)
     8             res.push_back(path);
     9         if (left)
    10             help(res, left, path, target - root->val);
    11         if (right)
    12             help(res, right, path, target - root->val);
    13         path.pop_back();
    14     }
    15     vector<vector<int>> pathSum(TreeNode* root, int sum) {
    16         vector<vector<int> > res;
    17         if (!root) return res;
    18         vector<int> path;
    19         help(res, root, path, sum);
    20         return res;
    21     }
    22 };
     
  • 相关阅读:
    IBM实习
    软件测试——一些想法
    ftp文件上传下载实用命令
    Json解析,Json-lib
    eclipse Swt编程—窗口小部件widget
    Java 泛型
    我的理想与现实
    Java泛型介绍——HashMap总结
    Java语言面向对象的一些基本特点
    Java的一些常见问题,JRE,JDK,JVM,包等概念理解
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5170950.html
Copyright © 2011-2022 走看看