zoukankan      html  css  js  c++  java
  • LeetCode 112. Path Sum路径总和 (C++)

    题目:

    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.

    Note: A leaf is a node with no children.

    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.

    分析:

    给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。

    从根节点判断是否存在一条到叶子节点的路径和等于目标和,等同于判断根节点的左右节点到叶子节点的路径和等于目标和减去根节点的值。

    从给的例子中来看,判断根节点5是否有路径和等于22,相当于判断根节点的左节点4是否有路径和等于22减去5,也就是17,继续计算下去,11的时候判断是否有路径和等于13,其左叶子节点等于7,不等于13-11,而右叶子节点为2,等于13-11,返回true。

    程序:

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        bool hasPathSum(TreeNode* root, int sum) {
            if(root == nullptr) return false;
            if(root->left == nullptr && root->right == nullptr && root->val == sum)
                return true;
            return hasPathSum(root->left, sum-root->val)||hasPathSum(root->right, sum-root->val);
        }
    };
  • 相关阅读:
    nyoj 202 红黑树
    nyoj 237 游戏高手的烦恼
    nyoj 203 三国志
    nyoj 118 修路方案
    nyoj 714 Card Trick
    nyoj 710 外星人的供给站
    nyoj 712探 寻 宝 藏
    nyoj 709 异 形 卵
    nyoj 711 最舒适的路线
    HTML5表格简单应用案例之[招聘需求表]
  • 原文地址:https://www.cnblogs.com/silentteller/p/10823183.html
Copyright © 2011-2022 走看看