zoukankan      html  css  js  c++  java
  • Leetcode OJ: Path Sum

    Path Sum

    Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

    For example:
    Given the below binary tree and sum = 22,

                  5
                 / 
                4   8
               /   / 
              11  13  4
             /        
            7    2      1
    

    return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

    判断是否存在“从根到叶”的路径使得其和为给定的值。面对这种问题直接上递归吧。递归关系就是:

    1. 当到叶子节点时,计算叶子节点值是否与当前要求的和相等

    2. hasPathSum(root, sum) = hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val)

    记住到叶子节点是判断相等关系的,因为每次递归时都会用要求的和减去当前节点时,到叶子节点时则只需要判断相等即可。

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     bool hasPathSum(TreeNode *root, int sum) {
    13         if (root == NULL)
    14             return false;
    15         if (sum == root->val && root->left == NULL && root->right == NULL)
    16             return true;
    17         return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
    18     }
    19 };
  • 相关阅读:
    Hive 2.1.1安装配置
    vi / vim 删除以及其它命令
    『MySQL』时间戳转换
    update 中实现子查询
    hive lateral view 与 explode详解
    xpath定位方法详解
    Python int与string之间的转化
    ORM、SQLAchemy
    python bottle 简介
    python wsgi 简介
  • 原文地址:https://www.cnblogs.com/flowerkzj/p/3616614.html
Copyright © 2011-2022 走看看